August 22, 2008

The ref and out Keywords in C#

In C# all value type parameters (objects that inherit from System.ValueType) are allocated to the stack and passed by value. This means that a copy of these variables is created and passed into the method being called. Since the parameter is a local copy its scope is limited to that method. See the following example below:
protected void Sample()
{
int x = 5;
//Writes 5 to the console
Console.WriteLine(x.ToString());
//Send a copy of x
Increment(x);
//Writes 5 to the console
Console.WriteLine(x.ToString());
}

protected void Increment(int incoming)
{
incoming++;
}
Note that the variable x is not changed by the Increment method. In most cases this behavior is desired. However, there are occasions when we may want to persist changes to a value type parameter beyond the scope of the method. This is where the ref and out keywords come into play. Here's our sample again but with the ref keyword used in the Increment method:
protected void Sample()
{
int x = 5;
//Writes 5 to the console
Console.WriteLine(x.ToString());
//Send a reference of x
Increment(ref x);
//Writes 6 to the console
Console.WriteLine(x.ToString());
}

protected void Increment(ref int incoming)
{
incoming++;
}
Note that this time around x is 6 after the Increment method is executed.

The ref and out keywords operate identically except that ref parameters must be initialized before being passed into the method while out parameters must be initialized by the time the method returns.

No comments: