Monday 26 November 2012

c sharp programming

Strings Are Immutable


One of the interesting aspects of System.String is that once you assign a string object with its initial
value, the character data cannot be changed. At first glance, this might seem like a flat-out lie, given that
we are always reassigning strings to new values and because the System.String type defines a number of
methods that appear to modify the character data in one way or another (such as uppercasing and

lowercasing). However, if you look more closely at what is happening behind the scenes, you will notice
the methods of the string type are, in fact, returning you a brand-new string object in a modified
format.

static void StringsAreImmutable()
{
  // Set initial string value.
  string s1 = "This is my string.";
  Console.WriteLine("s1 = {0}", s1);

  // Uppercase s1?
  string upperString = s1.ToUpper();
  Console.WriteLine("upperString = {0}", upperString);

  // Nope! s1 is in the same format!
  Console.WriteLine("s1 = {0}", s1);
}

No comments:

Post a Comment