Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Microsoft C# string documentation: Am I misinterpreting what I read, or is the documentation wrong?

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? :)

like image 509
Antonio Avatar asked Feb 09 '23 03:02

Antonio


1 Answers

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.

like image 189
juharr Avatar answered Feb 12 '23 02:02

juharr