Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking C# references

Tags:

c#

reference

I was wondering when and why references get broken in C#?

The following code example highlights this:

StringBuilder a = null, b = null;
a = new StringBuilder("a");
b = a;
b.Append("b");
b = null;
Console.WriteLine(a != null? a.ToString() : "null");
Console.WriteLine(b != null ? b.ToString() : "null");

//Output: 
    ab
    null

Why is it, for this example, that b's reference to a does not cause a to be null as well?

like image 843
Joey Ciechanowicz Avatar asked Nov 28 '22 00:11

Joey Ciechanowicz


1 Answers

You need to distinguish between variables, references and objects.

This line:

b = a;

sets the value of b to the value of a. That value is a reference. It's a reference to an object. At this point, making changes to that object via either a or b will just make changes to the same object - those changes would be visible via either a or b too, as both still have references to the same object.

They're like two pieces of paper with the same house address written on them though - the two variables don't know anything about each other, they just happen to have the same value due to the previous line.

So, when we change the value of b on this line:

b = null;

that just changes the value of b. It sets the value of b to a null reference. This makes no changes to either the value of a or the StringBuilder object which the old value of b referred to.

I have an article which goes into more details on this, and which you may find useful.

like image 109
Jon Skeet Avatar answered Dec 22 '22 10:12

Jon Skeet