Wednesday 27 February 2013

Immutable String

All strings in .NET are immutable. You never can change a content of any string. All string operations create a brand-new string

We know that strings are reference type in .net. Due to this fact, they are allocated on heap and when in the scope their pointer come on to the stack. When we try and assign a new value to a string variable, we can get the new value assigned to our variable, but in the background, a new memory location is allocated and its reference is copied to out string variable making us feel that the value of the original one is changed. This feature is referred as immutable. Thus all string in .net are immutable.
Due to this behavior of string we should always use StringBuilder class present in System.IO.Text namespace. System.Text.StringBuilder.Append does this thing much more effectively, because already available data is never copied again, the instance of StringBuilder mutates instead.

 if you have any repeated operation to compose a string, always use StringBuilder. Basically, using more than one string "+" in one expression is not very effective; string.Format function is much better, faster and more readable.


string myString = "Immutable";
char charI = myString[0];
//you can do it
//myString[0] = ' '; myString[1] = ' '; no way; it is immutable
//
array of char can be considered as some kind of string; it is mutable:
char[] myText = new char['M', 'u', 't', 'a', 'b', 'l', 'e', ' ', ];
myText[7] = '!';
//you can do it! The result will be "Mutable!"

No comments:

Post a Comment