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?
You need to distinguish between variables, references and objects.
This line:
sets the value of
bto the value ofa. That value is a reference. It’s a reference to an object. At this point, making changes to that object via eitheraorbwill just make changes to the same object – those changes would be visible via eitheraorbtoo, 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
bon this line:that just changes the value of
b. It sets the value ofbto a null reference. This makes no changes to either the value ofaor theStringBuilderobject which the old value ofbreferred to.I have an article which goes into more details on this, and which you may find useful.