Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
Mutable type, in C#, is a type of object whose data members, such as properties, data and fields, can be modified after its creation.
Mutable types are used in parallel applications, where the objects of mutable value type are maintained in the stack by the Common Language Runtime (CLR). This provides some optimization, which makes it faster than heap-allocated objects. To prevent synchronization errors from occurring in parallel applications due to multiple threads accessing the shared data, mutable types are used with some kind of locking mechanism.
Due to its inherent nature, mutable type data can get modified during run time, so mutable type is often used when the object contains a large amount of changeable data. Although mutable type is not as thread-safe and secure as immutable type, it is more often used with variables of value type, which get allocated in the stack, improving performance.
All built-in value types like int, double, etc., are mutable types and can be made immutable by adding the modifier "readonly" before the variables. If a mutable reference type is specified with a readonly modifier, the C# compiler generates a warning. By adding a readonly modifier to a field of reference type, the field cannot be replaced with another instance of the reference type, but will allow the instance data of the field to be modified through the reference type.
For example, StringBuilder is a mutable reference type in the .NET framework library, through which the string value of an instance created out of this type can be modified by appending, removing, replacing or inserting characters.
A mutable type should not be derived from an immutable type because there is a possibility of a virtual method in the derived class to override it such that the immutable members are overwritten.
The main limitation of mutable type is that while passing an object of mutable type (like struct) through assignment of a local variable or as a parameter to a method, the value of the object is transferred and not the object itself. By this, the copy of the object is mutated and not the original. This behavior may lead to unexpected bugs.