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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With