Can any one help me in finding the basic difference between mutable and immutable?
To summarise the difference, mutable objects can change their state or contents and immutable objects can't change their state or content. Immutable Objects : These are of in-built types like int, float, bool, string, unicode, tuple. In simple words, an immutable object can't be changed after it is created.
Mutable: Mutable means whose state can be changed after it is created. Immutable: Immutable means whose state cannot be changed once it is created.
a mutable string can be changed, and an immutable string cannot be changed.
Immutable means that once initialized, the state of an object cannot change.
Mutable means it can.
For example - strings in .NET are immutable. Whenever you do an operation on a string (trims, upper casing, etc...) a new string gets created.
In practice, if you want to create an immutable type, you only allow getters on it and do not allow any state changes (so any private field cannot change once the constructor finished running).
A very basic definition would be:
Mutable Objects: When you have a reference to an instance of an object, the contents of that instance can be altered
Immutable Objects: When you have a reference to an instance of an object, the contents of that instance cannot be altered
Immutable means "cannot be modified after it is created".
An example of an immutable type is DateTime. The method AddMinutes
does not modify the object - it creates and returns a new DateTime.
Another example is string. For a mutable class similar to string you can use the class StringBuilder
.
There is no keyword in C# to declare a type as immutable. Instead you should mark all member fields as readonly
to ensure that they can only be set in the constructor. This will prevent you from accidentally modifying one of the fields, breaking the immutability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With