Mutable Objects vs Immutable Objects in C#
C#, mutability and immutability refer to whether or not an object’s state can be changed after it has been created.
1. Mutable Objects
- A mutable object can be modified after its creation.
- This means the values of the object's fields or properties can be changed, either directly or through methods that modify its state.
- Classes are usually mutable in C#, but structs can also be mutable if designed that way.
Example of a Mutable Class
In the example above, Person is mutable because its Name and Age properties can be changed after an instance of Person is created.
2. Immutable Objects
- An immutable object cannot be changed after it is created.
- This means that all fields and properties of the object are set only once, typically through the constructor, and cannot be changed afterward.
- Immutable objects are useful when you want objects that don’t change over time, which can help prevent bugs, especially in multi-threaded scenarios.
- Examples of immutable types in C# include
System.String,System.DateTime, and other simple types.
Example of an Immutable Class
In this example, Point is immutable because it has only read-only properties (X and Y) that are set once in the constructor and cannot be changed afterward.
Why Use Immutable Types?
- Thread Safety: Immutable objects are inherently thread-safe because their state cannot change after construction.
- Predictability: Since immutable objects cannot change, they are easier to reason about and avoid side effects.
- Hash Codes and Dictionaries: Immutable objects work well as keys in dictionaries or hash sets because their hash codes won’t change over time.
Making Classes Immutable in C#
To create an immutable class in C#:
- Use
readonlyfields or properties with onlygetaccessors. - Set all values through a constructor.
- Avoid methods that modify state.
Immutable Example with a String
In the example above, string is immutable because any modification (like Replace) results in a new string rather than changing the original.
Mutable vs. Immutable Summary Table
| Feature | Mutable | Immutable |
|---|---|---|
| Can be changed after creation? | Yes | No |
| Common types | Classes (e.g., List, Array) | String, DateTime, custom immutable classes |
| Use cases | When state changes are expected | When stability and thread safety are preferred |
Comments
Post a Comment