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).