String is immutable - International Days

International Days

Internationally important Days


Home Top Ad

Post Top Ad

Tuesday, 28 July 2015

String is immutable

String is immutable 

  We heard that many times but most of us don't know what that means.
Here is the explanation for what is mutable and what is immutable..

 Mutable and immutable are merely just  English words as the meaning of these words 

  • 'Can change'  - Mutable
  • 'Cannot change'- Immutable

In .Net C# , we have 'string' object and 'StringBuilder' object


 String is immutable . That means a if we define a string it will create a sting object ,if we change the value of our sting then also create another sting object. If we try to concatenate it will also create another string object.

string immutableStr = string.Empty;
for (int i = 0; i < 100; i++)
    immutableStr = immutableStr + i.ToString();

In the above example , we the variable 'immutablestr' will be assigned 100 times. Each time new object is assigned for the same variable.


  StringBuilder is mutable string type. when stringbuilder is invoked, then allocate a memory for it and what happening is , append the new string to it. There wont be any extra memory allocation for StringBuilder.
System.Text.StringBuilder mutableStr = new System.Text.StringBuilder();
for (int i = 0; i < 100; i++)
    mutableStr = mutableStr.Append(i);

In above there wont be any new memory allocation inside for loop only appending data to the previous 'mutablestr' variable.

No comments:

Post a Comment

Post Bottom Ad