#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.
Pingback: #1,008 – What Happens When You Forget That Strings Are Immutable | 2,000 Things You Should Know About C#
Small possible typo: Below the example, it says a new string allocated as the result of the ‘+’ operation… i think you meant the result of the Replace method?
Thanks Christopher, good catch! Change made.