Antonio
Antonio

Reputation: 20306

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

Upvotes: 4

Views: 125

Answers (3)

juharr
juharr

Reputation: 32296

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.

Upvotes: 7

Antonio
Antonio

Reputation: 20306

Ok, I see the problem is that I was looking at Visual Studio 2005 documentation, which was simply wrong. The right updated documentation is here.

Note that the documentation had already been amended for Visual Studio 2008:

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 that new object is assigned to b. The string "h" is then eligible for garbage collection.

But, as correctly pointed out by juharr in the comments below, it was still wrong in the sense that "h" is interned and never garbage collected.

Upvotes: 2

Jürgen Steinblock
Jürgen Steinblock

Reputation: 31743

Looks like the documentation is wrong: d += "ello"; is a shortcut for d = d + "ello";

The string object itself is immutable but you assign a new string to an existing variable (d).

Upvotes: -1

Related Questions