CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
Strings Are Immutable
One of the interesting aspects of System.String is that after 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);
}
If you examine the relevant output that follows, you can verify that the original string object (s1) is
not uppercased when calling ToUpper(). Rather, you are returned a copy of the string in a modified
format.
s1 = This is my string.
upperString = THIS IS MY STRING.
s1 = This is my string.
The same law of immutability holds true when you use the C# assignment operator. To illustrate,
implement the following StringsAreImmutable2() method:
static void StringsAreImmutable2()
{
string s2 = "My other string";
s2 = "New string value";
}
Now, compile your application and load the assembly into ildasm.exe (see Chapter 1).
The following output shows what you would find if you were to generate CIL code for the
StringsAreImmutable2() method:
.method private hidebysig static void
{
// Code size
14 (0xe)
.maxstack 1
100
StringsAreImmutable2() cil managed