METHODS AND BEHAVIORS AKEEL AHMED
Overview Anatomy of a Method Modifiers Writing Your Own Class Methods Types of Parameters Named and Optional Parameters
Anatomy of a Method A method is really nothing more than a group of statements placed together under a single name. Methods are defined inside a class. Methods are the members of a class that perform an action. Through writing methods you describe the behavior of data. Methods are similar to functions, procedures, and modules found in other programming languages. Main( ) is a method you have already written as the entry point into your program
Anatomy of a Method
Modifiers A modifier is added to a type or a type member’s declaration to change or alter it or to indicate how it can be accessed. Previously you learned about and used the const modifier const is added to a declaration to indicate that a value is constant and cannot be changed
STATIC MODIFIER All Main( ) method headings must include the static modifier. Static is used in this context to indicate that a method belongs to the type itself rather than to a specific object of a class. Methods that use the static modifier are called class methods. A single copy of the method is made instead of copies for each object. Instance methods require that an object be instantiated before the method is accessed
ACCESS MODIFIERS Another type of modifier is an access modifier. It specifies the level of accessibility for types and their members C# includes the following accessibility modifiers:
Writing Your Own Class Methods
Types of Parameters C# offers both call by value and call by reference parameters. Call by Value: With call by value, a copy of the original value is made and stored in a separate, different memory location. If the method changes the contents of the variable sent to it, this does not affect the original value stored in the variable from the calling method. There are three other types of parameters available in C#: Ref out params
params , ref and out The params type facilitates sending a varying number of arguments into a method. When you use the keywords ref and out, call by reference is assumed. With call by reference, you send the address of the argument to the method The keywords differ in that the ref keyword cannot be used unless the original argument is initialized before it is sent to the method. This restriction does not exist for out. The out keyword is useful for methods that allow users to enter the variable’s value in a method, and have those values available back in the calling method when control returns.