Search content within the blog

Thursday, April 16, 2009

Difference between ref and out in c#

A variable to be sent as ref parameter must be initialized.
It is intended to be changed in the method to which it is passed.

A variable to be sent as out parameter dont need to be initialized
before being passed to a method, because it must be assigned in that method.
It is not intended to be changed, but intended to be assigned(or reassigned)
in the method to which it is passed.

A "ref" parameters need initialization BEFORE you call the function; "out"
does not.


The following will not compile:

string a;
f(ref a);


The following will compile:


string a;
g(out a);


Example.....
int x = 4;
DisplayWithRef(ref x);
Response.Write("With ref: 14=" + x.ToString());
DisplayWithOut(out x);
Response.Write("With out: 24=" + x.ToString());
DisplayWithoutRefAndOut(x);
Response.Write("Without ref and out: 4!=" + x.ToString());

private void DisplayWithRef(ref int x)
{
x += 10;
}


private void DisplayWithOut(out int x)
{
x = 14;
x += 10;
}

private void DisplayWithoutRefAndOut(int x)
{
x -= 20;
}

No comments:

Post a Comment