Team LiB   Previous Section   Next Section

8.2 Method Arguments

The 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-Z and a second method when you want to sort it from Z-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.[3] The parameter list follows the method name and is enclosed in parentheses. Each parameter's type is identified before the name of the parameter.

[3] The terms "argument" and "parameter" are often used interchangeably, though some programmers insist on differentiating between the parameter declaration and the arguments passed in when the method is invoked.

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 8-3 illustrates how you pass values into a method, in this case values of type int and float.

Example 8-3. Passing parameters
using System;

public class MyClass
{
    public void SomeMethod(int firstParam, float secondParam)
    {
        Console.WriteLine(
            "Here are the parameters received: {0}, {1}",
            firstParam, secondParam);
    }

}

public class Tester
{
    static void Main()
    {
        int howManyPeople = 5;
        float pi = 3.14f;
        MyClass mc = new MyClass();
        mc.SomeMethod(howManyPeople, pi);
    }
}
Output:
Here are the parameters received: 5, 3.14

Note that when you pass in a float with a decimal part (3.14) you must append the letter f (3.14f) to signal to the compiler that the value is a float and not a double.

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.

    Team LiB   Previous Section   Next Section