what is immutable and mutable?

 Posted by Hemanthlaxmi on 7/29/2011 | Category: C# Interview questions | Views: 4613 | Points: 40

Strings are immutable . What this means is application is that modifying a string creates new string data on the heap and modifies the pointer on the stack to point to the new location. The data on the heap that is not referenced from the stack will be cleared at garbage collection time, but until then it’s wasteful.

In comparison, StringBuilders are mutable . Modifications/additions to the stringbuilder will update the data in the heap instead of making copies of it each time.

(StringBuilder sb = new StringBuilder; sb.Add(“test”); sb.Add(” and test2?);

That code will create a pointer on the stack and a data value on the heap, update that data value to add the second string and that’s it. Doing the same with strings would have left an abandoned string data value on the heap of value “test” waiting on the GC.

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response

More Interview Questions by Hemanthlaxmi