Mutable Type

What Does Mutable Type Mean?

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.

Techopedia Explains Mutable Type

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.


Related Terms

Latest DevOps Terms

Related Reading

Margaret Rouse

Margaret Rouse is an award-winning technical writer and teacher known for her ability to explain complex technical subjects to a non-technical, business audience. Over the past twenty years her explanations have appeared on TechTarget websites and she's been cited as an authority in articles by the New York Times, Time Magazine, USA Today, ZDNet, PC Magazine and Discovery Magazine.Margaret's idea of a fun day is helping IT and business professionals learn to speak each other’s highly specialized languages. If you have a suggestion for a new definition or how to improve a technical explanation, please email Margaret or contact her…