#69 – Strings Are Immutable

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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

3 Responses to #69 – Strings Are Immutable

  1. Pingback: #1,008 – What Happens When You Forget That Strings Are Immutable | 2,000 Things You Should Know About C#

  2. Christopher Wodarczyk says:

    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?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: