What is the meaning of Immutable?

Immutable means once you create a thing, you cannot modify it.

In the context of .NET and programming in general, immutability refers to the characteristic of an object whose state cannot be modified after it is created. Once an immutable object is created, its state remains constant throughout its lifetime.

Here’s a more detailed breakdown:

  1. State cannot change: The data within an immutable object is fixed and cannot be altered after instantiation.
  2. Thread safety: Immutable objects are inherently thread-safe because their state cannot be changed. This eliminates the need for synchronization mechanisms in multi-threaded environments.
  3. Predictability: With immutable objects, you can rely on their state not changing unexpectedly, making your code easier to reason about and debug.
  4. Value semantics: Immutable objects are typically compared by their values rather than their references, simplifying equality checks and ensuring predictable behavior.

In .NET, some common examples of immutable types include string, DateTime, and various collection types like ImmutableArray and ImmutableList. Additionally, you can create your own immutable types by ensuring that their properties are read-only and their state cannot be modified once initialized.

For example: If you want give new value to old value then it will discard the old value and create new instance in memory to hold the new value.