on ASP.net Weblogs
See other posts from ASP.net Weblogs
or by nmarun
Published on Wed, 29 Dec 2010 14:44:00 GMT Indexed on 2010/12/29 14:54 UTC
Read the original article Hit count: 408
So the question is what is the point of passing a reference type along with the ref keyword?
I have an Employee class as below:
In my calling class, I say:
After having a look at the code, you’ll probably say,
Well, an instance of a class gets passed as a reference, so any changes to the instance inside the CallSomeMethod, actually modifies the original object. Hence the output will be ‘John-Doe’ on the first call and ‘Smith-Doe’ on the second.
And you’re right:
So the question is what’s the use of passing this Employee parameter as a ref?
The output is still the same:
Ok, so is there really a need to pass a reference type using the ref keyword? I’ll remove the ‘ref’ keyword and make one more change to the CallSomeMethod method.
In line 17 you’ll see I’ve ‘new’d up the incoming Employee parameter and then set its properties to new values. The output tells me that the original instance of the Employee class does not change.
Huh? But an instance of a class gets passed by reference, so why did the values not change on the original instance or how do I keep the two instances in-sync all the times?
Aah, now here’s the answer. In order to keep the objects in sync, you pass them using the ‘ref’ keyword.
Viola! Now, to prove it beyond doubt, I said, let me try with another reference type: string.
The output was as expected, first ‘abc’ and then ‘def’ - proves the 'ref' keyword works here as well.
Now, what if I remove the ‘ref’ keyword? The output should still be the same as the above right, since string is a reference type?
Wrong, the output shows ‘abc’ printed twice.
Wait a minute… now how could this be? This is because string is an immutable type. This means that any time you modify an instance of string, new memory address is allocated to the instance. The effect is similar to ‘new’ing up the Employee instance inside the CallSomeMethod in the absence of the ‘ref’ keyword.
Verdict: ref key came to the rescue and saved the planet… again!
© ASP.net Weblogs or respective owner