#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 comment