Using a ref parameter on a reference variable

  • Thread starter Thread starter Edward Diener
  • Start date Start date
E

Edward Diener

My undersstanding of using a ref parameter is to be able to pass initialized
value variables as references. Is there any purpose to using a ref paraneter
with a reference variable ? If one does it the compiler accepts it. Does
this mean anything ?
 
Hi Edward,

Um, could you clarify what you mean?
If you want the original reference to change according to changes
made inside a method referencing a reference variable is very useful.

MyObject mo = new MyObject()

DoStuff(ref mo);
DoMoreStuff(mo);
....

private void DoStuff(ref MyObject m1)
{
if(unsatisfactory)
m1 = new MyObject();
...
}

private void DoOtherStuff(MyObject m2)
{
// m2 would not be the same as m1 without ref
}
 
In other words, passing a reference as a ref allows one to change the
reference itself as well as using the object to which the reference refers.
 
Hi Edward:

Yes, it is possible to pass a reference type as a ref parameter. Doing
so means the method can change the value of the reference type as seen
by the caller. In other words, it could set the ref parameter to null,
and the caller would have a null reference when the method completes.

See Jon's document:
http://www.yoda.arachsys.com/csharp/parameters.html#check
 
Edward Diener said:
My undersstanding of using a ref parameter is to be able to pass initialized
value variables as references.

No. It's to pass a parameter *by* reference. There's a big difference.
Is there any purpose to using a ref paraneter with a reference variable ?
Yes.

If one does it the compiler accepts it. Does this mean anything ?

Yes.

Compare:

void DoNothing (string s)
{
s = "something";
}

void DoesSomething (ref string s)
{
s = "something";
}

The first of these is a no-op; the second will change the value of the
variable passed (by reference) to a reference to the string
"something".

See http://www.pobox.com/~skeet/csharp/parameters.html for more
information.
 
Back
Top