Being new to C#, I was reading some guide. About strings, here I read (highlighting is mine):
Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and the variable b continues to hold "h".
string b = "h"; b += "ello";
But trying the following code, it prints "hello".
string b = "h";
b += "ello";
System.Diagnostics.Debug.WriteLine(b);
So, am I misinterpreting what I read, or is the documentation wrong? Any other option? :)
Clearly the documentation is wrong and as you have already found a latter version has been corrected, although it too has some issues (See below). But I think a better example would be
string b = "h";
string d = b;
d += "ello";
Now b
is still "h" because the +=
did not update the reference, but create a new string
that d
references.
Also it should be noted that there are 3 strings
in this code. First the string
literal "h", then the string
literal "ello" and finally the string
"hello" that is created from the concatenation of the previous two. Because all string
literals are interned and interned strings are not garbage collected the only string
of the 3 that will eventually be eligible for garbage collection is the "hello" that is currently referenced by d
. Although it is possible to turn string
interning off in which case all three would eventually be eligible for garbage collection.
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