Similarities
The ref and out keyword's pass a reference of a variable to a method, thus using the original variable and not a new instance. By default arguments are passed as value types, a copy of the variable is sent rather than the original variable itself. This is shown in the example below.
class Program
{
public void ValueMethod(int i)
{
i += 25;
Console.WriteLine("Value Method: i value = {0}", i);
}
static void Main(string[] args)
{
var p = new Program();
int counter = 1;
//passing a value type to the method by default
p.ValueMethod(counter);
Console.WriteLine("Main: Counter Value is: {0}", counter);
}
}
Output:
Value Method: i value = 26
Main: Counter Value is: 1
A property is not a variable and cannot be passed as a ref/out parameter. If you try and use it like this;
p.ValueMethod(ref person.Age);
the compiler will give you the following error: 'ref' argument is not classified as a variable
Overloaded methods will be created if two methods are created with the same name and variables, but the ref/out keyword is used with one of them, for example
public void ValueMethod(int i)
public void ValueMethod(ref int i)
If the same is done, using ref and out in the signature the compiler will give an error: Member with the same signature is already used.
Differences
The ref keyword requires the variable to be initialized before passing it to the method, out does not require the variable to be initialized. If the ref parameter is not initialized, the compiler will give an error: Use of unassigned local variable, 'i'.
class Program
{
public void ValueMethod(int i)
{
i += 25;
Console.WriteLine("Value Method: i value = {0}", i);
}
public void RefMethod(ref int i)
{
i = 2;
}
public void OutMethod(out int i)
{
i = 5;
}
static void Main(string[] args)
{
var p = new Program();
int i = 10;
int x;
p.RefMethod(ref i);
p.OutMethod(out x);
Console.WriteLine("Main: x is: {0}", x);
}
}
Another difference is, the out parameter must be assigned in the method, otherwise the compiler will give an error: The out parameter 'i' must be assigned to before control leaves the current method.
Example:
public void OutMethod(out int i)
{
int j = 5;
}
As you can see the difference is subtle, and always good to know.