The Methods of a Class |
|
In the body of a method, you can declare one or more variables that would be used only by the method. A variable declared in the body of a method is referred to as a local variable. The variable cannot be accessed outside of the method it belongs to. After declaring a local variable, it is made available to the method and you can use it as you see fit, for example, you can assign it a value prior to using it.
|
If a method has carried an assignment and must make its result available to other methods or other classes, the method must return a value and cannot be void. To declare a method that returns a value, provide its return type to the left of its name. Here is an example: using System; class Exercise { static double Operation() { } static void Main() { } } After a method has performed its assignment, it must clearly demonstrate that it is returning a value. To do this, you use the return keyword followed by the value that the method is returning. The value returned must be of the same type specified as the return type of the method. Here is an example: using System; class Exercise { static double Operation() { return 24.55; } static void Main() { } } A method can also return an expression, provided the expression produces a value that is conform to the return type. Here is an example: using System; class Exercise { static double Operation() { return 24.55 * 4.16; } static void Main() { } } When a method returns a value, the compiler considers such a method as if it were a regular value. This means that you can use the Console.Write() or the Console.WriteLine() method to display its value. To do this, simply type the name of the method and its parentheses in the Console.Write() of the Console.WriteLine() methods' parentheses. Here is an example: using System; class Exercise { static double Operation() { return 24.55; } static void Main() { Console.WriteLine(Operation()); } } In the same way, a method that returns a value can be assigned to a variable of the same type.
|
|
||
Home | Copyright © 2006-2007 FunctionX, Inc. | Next |
|