Immutable Data Structure - C#

Immutable Data Structure - C#

an unconventional type from a mutable world

ยท

2 min read

What is immutability?

Immutable types are the types that once initialized then never be changed their internal state after that.

In a simple sentence, mutation means editable and immutation means opposite of it (not editable)!

A very good example to start on is String and StringBuilder class in dotnet/java where String is the immutable data type and StringBuilder is mutable. Another very common datatype in .net is DateTime (it's also immutable).

So what are the benefits of being immutable?

  • Thread Safe.
  • Defensive copy.
  • Valid state.
  • Using DTO.

Being Thread Safe:

When we encounter any concurrent thread operation, there is a concept called thread-safe data types. Actually what it means or what it does that ensures two/more threads cannot change a value at the same time. It keeps the data integrity issue aside. When it comes to the threads it always comes to the memory access simultaneously at the same piece. As long as those data types are immutable, working with thread becomes much more easier.

Defensive Copy:

If you are copying from an object to another object you have to deep copy the instance that itself is an overhead of o(n) complexity itself

Valid state:

When you are working with immutable objects, you will know they will always remain safe by their nature. No other thread or background process or even any method cannot change without your direct knowledge.

Using DTO:

A DTO has only one goal, which is to transfer the exact data without any modification. In such scenarios, having immutable collections for DTO is most desirable.

check StackOverflow question for more immutable C#

Immutability is a first-class citizen to any functional programming paradigms whereas in c#, having a mutable object is the norm and I think that also okay.

My take:

If your application takes advantage of multi-threading then creating immutable objects should be first priority of your architectural design.

Note Sections (Further study)

  1. Pass by value & pass by parameter

  2. it's a great talk by Spencer Using Immutable DS