Thursday, September 25, 2008

RE: What is meant by Mutable and Immutable classes?

Hi Sanjiv, I am a bit confused here.

String is a immutable class. It is advised if the value of the string
varaible is going to change from time to time then we use a StringBuilder which is a mutable class.

Hence when u change the value of as instance of string object (instance of immutable class) then new memory is created and value is stored in the new memory, where as if you assign a new value to an instance of StringBuilder class then value is changed in the same memory and this gives a performance improvement.

So in case if the string is frequently changed in the code at run time, it is advisable to use mutable objectes.


Is this answer useful? Yes | No
February 18, 2008 20:34:40 #4
amitkumar316 Member Since: February 2008 Contribution: 9
RE: What is meant by Mutable and Immutable classes?
immutable classes are read-only classes. once declared their value cannot be changed & its vice-versa are mutable classes.

Is this answer useful? Yes | No
July 30, 2008 11:16:30 #5
bobby420 Member Since: July 2008 Contribution: 1
RE: What is meant by Mutable and Immutable classes?
Best Example to understand Mutable and Immutable is string.
string class is immutable.
so if
string x = "123";
if you do x = x + "abc" what it does is it assigns new memory location for 123 and abc.
Then adds the two strings and places the computed results in new memory location and points x to it.

if you use
System.Text.StringBuilder sb = new System.Text.StringBuilder("123");
sb.Append("abc");
x=sb.ToString();

stringbuilder is mutable class. It just adds the string to same memory location.
This way string manipulation is faster.

I hope this helps.

No comments: