String immutability and StringBuilder

A string can never be changed after it is created. "Modifying" one always builds a new string.

Time s += x is O(n)Space a new string each timeCode C#
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 buffer

Tips

In the .NET library

Use StringBuilder for loops, string.Join or string.Concat for collections, and interpolation ($"...") for a fixed handful of parts.