Information Technology Reference
In-Depth Information
Methods
A method is a named block of executable code that can be executed from many different parts
of the program, and even from other programs. (There are also anonymous methods, which
aren't named—but I'll cover these in Chapter 15.)
When a method is called , or invoked , it executes its code, and then returns to the code that
called it. Some methods return a value to the position from which they were called. Methods
correspond to member functions in C++.
The minimum syntax for declaring a method includes the following components:
￿
Return type : This states the type of value the method returns. If a method does not return
a value, the return type is specified as void .
￿
Name : This is the name of the method.
￿
Parameter list : This consists of at least an empty set of matching parentheses. If there are
parameters (which will be covered in the next chapter), they are listed between the
parentheses.
￿
Method body : This consists of a matching set of curly braces, containing the execut-
able code.
For example, the following code declares a class with a simple method called PrintNums .
From the declaration, you can tell the following about PrintNums :
It returns no value; hence, the return type is specified as void .
￿
￿ t has an empty parameter list.
￿
It contains two lines of code in its method body.
class SimpleClass
{
Return type Parameter list
void PrintNums ( )
{
Console.WriteLine("1");
Console.WriteLine("2");
}
}
Note Unlike C and C++, there are no global functions (i.e., methods or functions) declared outside of a
type declaration.
Search WWH ::




Custom Search