#69 – Strings Are Immutable
August 25, 2010 3 Comments
In C#, strings are immutable which means that they cannot be changed after they are created. More generally, this is the case for the System.String class in .NET.
Syntactically, however, it appears that you can change the contents of a string (e.g. add a character to the end of a string):
string s1 = "AGORA"; s1 = s1.Replace('A', 'Z'); // Replace A's with Z's
But in this case, the original string is destroyed, a new string is allocated that contains the result of the replace operation and the s1 variable is set to point to the new string.
In practice, it doesn’t matter much to the programmer that C# strings are internally immutable, since you can “change” them syntactically, as shown above. Immutability is important only when considering performance of repeated operations on the same string.