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.[10] 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 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(); ...

Get Learning C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.