Within the .NET Framework, strings are immutable. This means that a string cannot be changed after it has been created. For example, suppose you create a string as follows:
String x = "Hello World";
The string "Hello World" appears on the managed heap and x contains a reference to that string. To optimize the CLR, strings were made immutable. Examine the following three lines of code:
String x = "Hello World"; x += " from "; x += " C# 2005 Unleashed by SAMS Publishing";
Developers with experience in other languages might expect that the x variable is initialized with "Hello World" and then is dynamically expanded twice to first add "from" and then add the remaining string literal.
Here's what actually happens: Three different strings are created on the managed heap, and each time a new one is created, the x variable shifts to point to the newly created string. Because strings are immutable, any change to an existing string creates a new string stored on the heap. Interim strings that are out of scope (such as "from") will eventually be collected by the garbage collector. Figure 16.1 illustrates what happens to the managed heap as a string is concatenated using the += operator.
Figure 16.1. String concatenation on the managed heap.
To avoid the problems that arise from repeated string concatenation using the += operator, you should instead use the StringBuilder class, as shown in the following example:
StringBuilder sb = new StringBuilder(); sb.Append("Hello World"); sb.Append(" from "); sb.Append("C# 2005 Unleashed by SAMS Publishing");
The StringBuilder class also has an AppendFormat method that allows you to format a string at the same time it is being appended, which comes in handy. To access the string within the StringBuilder, simply use the ToString() method as shown: