String immutability and StringBuilder
A string can never be changed after it is created. "Modifying" one always builds a new string.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
s += "!" allocates a new string holding the old characters plus the new one, then points s at it. The old string is untouched, which is why t still sees "Hi".
Code
string s = "Hi";
string t = s;
s += "!"; // builds a NEW string
Console.WriteLine(t); // still "Hi"
var sb = new StringBuilder("Hi");
sb.Append("!"); // changes the same bufferTips
- Concatenating in a loop copies the growing string every time, which is O(n²) overall.
- Because strings cannot change, they are safe to share between threads and to use as dictionary keys.
In the .NET library
Use StringBuilder for loops, string.Join or string.Concat for collections, and interpolation ($"...") for a fixed handful of parts.