Thursday, October 4, 2007

Mutable and Immutable Class

Immutable type are types whose instance data, fields and properties, does not change after the instance is created. Most value types are immutable, but the mutable type are A type whose instance data, fields and properties, can be changed after the instance is created. Most Reference Types are mutable. Shortly we can say as: When you have a reference to an instance of an object, the contents of that instance can be altered for Mutable objects and When you have a reference to an instance of an object, the contents of that instance cannot be altered for Immutable objects.



String is a immutable class. It is advised if the value of the stringvaraible 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.

No comments: