Wednesday, August 10, 2011

Object are passed by reference

Passing values in c# is really misunderstood by many people.

Let's understand this concept by few examples:

StringBuilder first = new StringBuilder();
StringBuilder second = first;
first.Append ("hello");
first = null;
Console.WriteLine (second);
 
Output: Hello

When we assign reference to second of first, we are acutally assigning the object reference contact by first. So when we set first to null, now first is not refering to any object, however second is still referening to that object.

Now
void Foo (StringBuilder x)
{
    x = null;
}

...

StringBuilder y = new StringBuilder();
y.Append ("hello");
Foo (y);
Console.WriteLine (y==null);
 
Output: False Interesting right! Actually when we are passing object by reference, we are not passing the actual 
reference to first object, instead we are just passing hte values. 
 
The value of a reference type variable is the reference - if two reference type 
variables refer to the same object, then changes to the data in that object will 
be seen via both variables.

No comments: