Partager via


Methods (C# Programming Guide) 

A method is a code block containing a series of statements. In C#, every executed instruction is done so in the context of a method.

Methods are declared within a class or struct by specifying the access level, the return value, the name of the method, and any method parameters. Method parameters are surrounded by parentheses, and separated by commas. Empty parentheses indicate that the method requires no parameters. This class contains three methods:

class Motorcycle
{
    public void StartEngine() { }
    public void AddGas(int gallons) { }
    public int Drive(int miles, int speed) { return 0; }
}

Calling a method on an object is similar to accessing a field. After the object name, add a period, the name of the method, and parentheses. Arguments are listed within the parentheses, and separated by commas. The methods of the Motorcycle class can therefore be called like this:

Motorcycle moto = new Motorcycle();

moto.StartEngine();
moto.AddGas(15);
moto.Drive(5, 20);

Method Parameters

As shown in the previous code snippet, passing arguments to a method is simply a matter of providing them in the parentheses when calling a method. To the method being called, the incoming arguments are called parameters.

The parameters a method receives are also provided in a set of parentheses, but the type and a name for each parameter must be specified. The name does not have to be the same as the argument. For example:

public static void PassesInteger()
{
    int fortyFour = 44;
    TakesInteger(fortyFour);
}
static void TakesInteger(int i)
{
    i = 33;
}

Here a method called PassesInteger passes an argument to a method called TakesInteger. Within PassesInteger, the argument is named fortyFour, but in TakeInteger, this is a parameter named i. This parameter exists only within the TakesInteger method. Any number of other variables can be named i, and they can be of any type, so long as they are not parameters or variables declared inside this method.

Notice that TakesInteger assigns a new value to the provided argument. One might expect this change to be reflected in the PassesInteger method once TakeInteger returns, but in fact the value in the variable fortyFour remains unchanged. This is because int is a value type. By default, when a value type is passed to a method, a copy is passed instead of the object itself. Because they are copies, any changes made to the parameter have no effect within the calling method. Value types get their name from the fact that a copy of the object is passed instead of the object itself. The value is passed, but not the same object.

For more information on passing value types, see Passing Value-Type Parameters (C# Programming Guide). For a list of value types integral to C#, see Value Types Table (C# Reference).

This differs from reference types, which are passed by reference. When an object based on a reference type is passed to a method, no copy of the object is made. Instead, a reference to the object being used as a method argument is made and passed. Changes made through this reference will therefore be reflected in the calling method. A reference type is created with the class keyword, like this:

public class SampleRefType
{
    public int value;
}

Now, if an object based on this type is passed to a method, it will be passed by reference. For example:

public static void TestRefType()
{
    SampleRefType rt = new SampleRefType();
    rt.value = 44;
    ModifyObject(rt);
    System.Console.WriteLine(rt.value);
}
static void ModifyObject(SampleRefType obj)
{
    obj.value = 33;
}

This example essentially does the same thing as the previous example. But, because a reference type is used, the modification made by ModifyObject is made to the object created in the TestRefType method. The TestRefType method will therefore display the value 33.

For more information, see Passing Reference-Type Parameters (C# Programming Guide) and Reference Types (C# Reference).

Return Values

Methods can return a value to the caller. If the return type, the type listed before the method name, is not void, then the method can return the value using the return keyword. A statement with the keyword return followed by a value that matches the return type will return that value to the method caller. The return keyword also stops the execution of the method. If the return type is void, a return statement with no value is still useful to stop the execution of the method. Without the return keyword, the method will stop executing when it reaches the end of the code block. Methods with a non-void return type are required to use the return keyword to return a value. For example, these two methods use the return keyword to return integers:

class SimpleMath
{
    public int AddTwoNumbers(int number1, int number2)
    {
        return number1 + number2;
    }

    public int SquareANumber(int number)
    {
        return number * number;
    }
}

To use a value returned from a method, the calling method can use the method call itself anywhere a value of the same type would suffice. You can also assign the return value to a variable. For example, the following two code examples accomplish the same goal:

int result = obj.AddTwoNumbers(1, 2);
obj.SquareANumber(result);
obj.SquareANumber(obj.AddTwoNumbers(1, 2));

Using an intermediate variable, in this case, result, to store a value is optional. It may help the readability of the code, or it may be necessary if the value is going to be used more than once.

For more information, see return (C# Reference).

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 1.6.5 Methods

  • 10.5 Methods

See Also

Reference

Objects, Classes and Structs (C# Programming Guide)
Access Modifiers (C# Programming Guide)
Static Classes and Static Class Members (C# Programming Guide)
Inheritance (C# Programming Guide)
params (C# Reference)
return (C# Reference)
out (C# Reference)
ref (C# Reference)
Passing Parameters (C# Programming Guide)

Concepts

C# Programming Guide