In C#, what is the difference between ref
and out
parameter?
Example:
void method1(ref int p1)
{
//....
}
void method2(out int p2)
{
//....
}
Also, what are the guidelines for the use of each?
In C#, what is the difference between ref
and out
parameter?
Example:
void method1(ref int p1)
{
//....
}
void method2(out int p2)
{
//....
}
Also, what are the guidelines for the use of each?
Both a ref parameter and an out parameter make an alias of a variable. That is, when you say:
M(int x) { ... }
...
int y = 123;
M(y);
then the value of y is passed, and x gets a copy of that value.
When you say
N(ref int x) { ... }
...
int y = 123;
N(ref y);
Then x and y are two names for the same variable. A change to x makes a change to y.
The only difference between ref and out from the caller's perspective is that the variable aliased by ref must be definitely assigned before the call. This is legal:
O(out int x) { ... }
...
int y; // no initialization!
O(out y);
But this is not:
N(ref int x) { ... }
...
int y; // no initialization!
N(ref y);
The only differences from the callee's perspective are:
ref
parameter can be assumed to be initially assigned; an out
parameter cannot.an out
parameter must be assigned before control leaves the method normally. That is, this is illegal:
void O(out int x) { return; }
x
must be assigned before the return.
Behind the scenes, ref
and out
have the same implementation; the only difference is how the compiler tracks whether variables are assigned or not.
The guidelines for their use are:
Straight from MSDN documentation:
The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed.
Source:http://msdn.microsoft.com/en-US/library/t3c3bfhx(v=vs.80).aspx
I feel that's clear enough. If this doesn't answer your question, let me know.
Another copy-paste of an example for the lazy:
class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value;
Method(out value);
// value is now 44
}
}
So in this case, if it were Method(ref int i)
instead, that method would require that i
be initialized first.