#1,008 – What Happens When You Forget That Strings Are Immutable

Strings in C# (the System.String type) are immutable.  Functions that act upon a string never change the instance of the string, but instead return a new instance of a string.

For example, to replace a portion of a string, you call the Replace method, assigning the result to the original string (or to a new string).

            quote = quote.Replace("Hell", "Minnesota");

If you forget that a string is immutable, you may forget to assign the result of this call to something.  The compiler won’t warn you about this.

            string quote = "Go to Heaven for the climate, Hell for the company.";
            Console.WriteLine(quote);

            // Does NOT change quote.  Rather, it creates
            // a new string, which we don't store anywhere
            quote.Replace("Hell", "Minnesota");

            Console.WriteLine(quote);

The string is not changed, as we might have expected.
1008-001

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.

One Response to #1,008 – What Happens When You Forget That Strings Are Immutable

  1. Pingback: Dew Drop – January 10, 2014 (#1699) | Morning Dew

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: