ref keyword on reference types?

  • Thread starter Thread starter Dennis Myrén
  • Start date Start date
D

Dennis Myrén

Hi.

Is there any difference between
void Method ( MyReferenceType myReferenceType )
and
void Method ( ref MyReferenceType myReferenceType )

(MyReferenceType is a class)

The MyReferenceType is indeed a reference type, so the two statements above
should be equal?
Or could it be that the ref keyword uses the same pointer, where not using
ref keyword creates a new pointer?

Anyhow, I would like to use the most efficient.

Thank You.
 
Dennis,

The statements are not equal. When you use the ref keyword and it is
applied to a reference type, it means that you can change the reference in
the method that the variable passed in for the parameter myReferenceType
points to.

The following code will show you:

public static void ReferenceTest1(string someString)
{
// Set the string to something else.
someString = "ReferenceTest1";
}

public static void ReferenceTest2(ref string someString)
{
// Set the string to something else.
someString = "ReferenceTest2";
}

// Now call both.
string pstrValue = "original value"

// Call the first method.
ReferenceTest1(pstrValue);

// This will output "original value"
Console.WriteLine(pstrValue);

// Call the second method.
ReferenceTest2(ref pstrValue);

// This will output "ReferenceTest2".
Console.WriteLine(pstrValue);

Hope this helps.
 
Nope, they're not the same:

Think of it like this: Lets say we have a Widget class with a property named
"prop", set to 0 in the constructor...

We have these two methods:

void RefMethod(ref Widget someObj) { someObj.prop = 1; someObj = new
Widget("B");}
void Method(Widget someObj){ someObj.prop = 2; someObj = newWidget("C"); }

And then this code:
....
Widget widget = new Widget("A");
// widget var now references Widget "A", widget.prop is 0
Method( a);
// widget var still references Widget "A", widget.prop is now 2. Widget "C"
may be garbage collected.
RefMethod( ref a);
// widget var now references Widget "B", widget.prop is now 0. Widget "A"
may be garbage collected.


Hope this helps!
 
Dennis Myrén said:
Is there any difference between
void Method ( MyReferenceType myReferenceType )
and
void Method ( ref MyReferenceType myReferenceType )

Yes there is.
(MyReferenceType is a class)

The MyReferenceType is indeed a reference type, so the two statements above
should be equal?

Nope - because passing a reference by value and passing a reference
variable *by* reference are very different.

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