C# Methods, Part 2 - The out keyword
(Page 4 of 5 )
The out parameter modifier keyword has the same effects as the ref keyword, with one important difference. With the ref keyword, you must initialize the variable before you pass it as the method parameters, but with the out keyword you can initialize the variable inside the method as follows:
using System;
namespace MyCompany
{
public class MethodTest
{
static void Main()
{
int ValueType;
TakeNumber(out ValueType);
Console.WriteLine("After calling the method the value of" + "the variable ValueType = {0}", ValueType);
Console.ReadLine();
}
static void TakeNumber(out int x)
{
x = 10;
Console.WriteLine("Inside the method we initialized x, x = {0}", x);
x++;
Console.WriteLine("we increased x by one inside the method, x = {0}", x);
}
}
}
The result will be:

We have passed an uninitialized variable to the method, and then we have initialized the variable inside the method. Note that the effects of the out keyword are the same as the ref keyword, so it's considered pass by reference behavior.
Next: Variable Length Parameters >>
More C# Articles
More By Michael Youssef