Strings are Immutable!

Working with strings is a common task in most apps but there are several ‘gotchas’ that can arise due to the immutable nature of a  String in .NET.

Immutable simply means that once created it doesn’t change. This seems strange at first since the value of a string variable can indeed be altered :

string s1 = "Initial Value";
s1 = "Updated Value";
Literal1.Text = s1;

In the above code the Literal will output the text “Updated Value” which seems to demonstrate the String s1 has been changed. However, behind the scenes a new object has actually been created by the .NET Framework and the variable s1 has been pointed to that (note the the original string object is still held in memory until the Garbage Collection is automatically run by the .NET Framework and so working with strings can consume a lot of memory if care isn’t taken).

The impact of strings being immutable is normally felt when manipulating them through the methods provided in the Framework:

string s1 = "Initial Value";
s1.ToUpper();
Literal1.Text = s1;

In the above snippet, we may think calling ToUpper() should convert the string to upper case and so the Literal should output “INITIAL VALUE” but instead the output is still “Initial Value”. A string is immutable! It cannot be changed, all the method ToUpper() does is return a new string of upper case values for the s1 string. The original string (s1 in this case is left unchanged).
To alter the actual string we will need to reassign its value:

string s1 = "Initial Value";
s1 = s1.ToUpper();
Literal1.Text = s1;

This results in the expected output of uppercase.

Note that the same holds true all the common methods of string manipulation such as Replace(), Remove(), Trim(), Insert().

For example, the below code will leave the original string s1 totally unchanged:

string s1 = "Initial xx";
s1.Replace("xx", "Value");
Literal1.Text = s1;

Instead it needs to be rewritten:

string s1 = "Initial xx";
s1 = s1.Replace("xx", "Value");
Literal1.Text = s1;

Note that it is  more efficient from both a code and memory perspective to leave the original string unaltered and simply output the new string values as required:

string s1 = "Initial xx";
Literal1.Text = s1.Replace("xx", "Value");

Hope this helps clarify a common issue in handling strings in .NET.

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!