Any succinct explanations?
Also Answered in: Difference between ref and out parameters in .NET
For the caller:
For the method:
So:
int x;
Foo(ref x); // Invalid: x isn't definitely assigned
Bar(out x); // Valid even though x isn't definitely assigned
Console.WriteLine(x); // Valid - x is now definitely assigned
...
public void Foo(ref int y)
{
Console.WriteLine(y); // Valid
// No need to assign value to y
}
public void Bar(out int y)
{
Console.WriteLine(y); // Invalid: y isn't definitely assigned
if (someCondition)
{
// Invalid - must assign value to y before returning
return;
}
else if (someOtherCondition)
{
// Valid - don't need to assign value to y if we're throwing
throw new Exception();
}
else
{
y = 10;
// Valid - we can return once we've definitely assigned to y
return;
}
}
Most succinct way of viewing it:
ref = inout
out = out
Ref and out parameter passing modes are used to allow a method to alter variables passed in by the caller. The difference between ref and out is subtle but important. Each parameter passing mode is designed to apply to a slightly different programming scenario. The important difference between out and ref parameters is the definite assignment rules used by each.
The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the callee is required to assign to the out parameter before returning.
source: MSDN
From the MSDN article that Alex mentions,
The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the callee is required to assign to the out parameter before returning.
In contrast ref parameters are considered initially assigned by the callee. As such, the callee is not required to assign to the ref parameter before use.
So to sum up, inside the method you can consider ref parameters to be set, but not out parameters - you must set these. Outside the method they should act the same.
Check out this Jon Skeet article about params in c#: