This is taken from Jon Skeet’s excellent personal C# site (http://www.yoda.arachsys.com/csharp/):
StringBuilder first = new StringBuilder(); StringBuilder second = first; first.Append ('hello'); first = null; Console.WriteLine (second);
1) Changing the value of first will not change the value of second –
2) although while their values are still references to the same object, any changes made to the object through the first variable will be visible through the second variable.
This is taken from the same sentence. What is meant by changing the value? I assume the value of a variable (eg int x = 4, or 5, or 45, etc).
Does this mean if first points to another compatible object, it won’t have an effect on two?
Everything on that page makes sense, I think it’s just an issue with my interpretation of the English.
Thanks
firstis a reference to an object of typeStringBuilder. That is,firststores a value that can be used to refer to an object on the heap that is type ofStringuilder.secondis another reference to an object of typeStringBuilderand its value is initially set refer to the same object thatfirstis referring to.If you change the value of
firstwhat you are doing is changing what the referent is. That is, you are usingfirstto refer to a different object. This does not impactsecond; its value is unaffected by changes to the value offirst. (Remember: the value offirstandsecondare references that initially have the same referent. But just like withdoes not change the value of
y, changing the value offirstdoes not change the value ofsecond.On the other hand, when
firstandsecondrefer to the same object, any changes to that object will be visible through bothfirstandsecond.Think of it like this. Let’s say I create a text file
first.htmlwhose contents areand I issue the command
copy first.html second.html. Then both pages can be used to refer to the same webpage; by following the link we arrive at the same referent. If changes are made to the Stack Overflow home page, then accessing the homepage through eitherfirst.htmlorsecond.htmlwill allow me to see those changes. But if I then change the contents offirst.htmlto bethen I can no longer use
first.htmlto refer to the Stack Overflow homepage. Moreover, this change does not impact the value ofsecond.html. It is stillThink of the contents of these files as the values of a reference type, and the ultimate desination as the referent object.