7.2. Method ArgumentsThe behavior of a class is defined by the methods of that class. To make your methods as flexible as possible, you can define parameters : information passed into the method when the method is invoked. Thus, rather than having to write one method when you want to sort your listbox from A to Z and a second method when you want to sort it from Z to A, you define a more general Sort( ) method and pass in a parameter specifying the order of the sort. Methods can take any number of parameters . The parameter list follows the method name and is enclosed in parentheses. Each parameter's type is identified before the name of the parameter.
For example, the following declaration defines a method named MyMethod( ) that returns void (that is, it returns no value at all) and takes two parameters (an int and a Button ): void MyMethod (int firstParam, Button secondParam) { // ... } Within the body of the method, the parameters act as local variables , as if you had declared them in the body of the method and initialized them with the values passed in. Example 7-2 illustrates how you pass values into a method; in this case, values of type int and float . Example 7-2. Passing parameters
Here is the output: Here are the parameters received: 5, 3.14
The method SomeMethod( ) takes two parameters, firstParam and secondParam , and displays them using Console.WriteLine( ) . FirstParam is an int , and secondParam is a float . These parameters are treated as local variables within SomeMethod( ) . You can manipulate these values within the method, but they go out of scope and are destroyed when the method ends. In the calling method ( Main ), two local variables ( howManyPeople and pi ) are created and initialized. These variables are passed as the parameters to SomeMethod( ) . The compiler maps howManyPeople to firstParam and pi to secondParam , based on their relative positions in the parameter list. |