protected void Sample()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:
{
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++;
}
protected void Sample()Note that this time around x is 6 after the Increment method is executed.
{
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++;
}
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.