Monday, October 12, 2009

Immutability in C#

Recently I was coming across with Patrick Smacchia's blog. He was talking about "Immutabiltiy". He says "There is a powerful and simple concept in programming that I think is really underused: Immutability".
He says that, make the objects immutable if their state is not going to change during the course of time. In this way we are avoiding the additional overhead of maintaining synchronization between the threads in mutithreaded applications.

The following are the 3 great benefits of Immutable objects
  • Simplify Muti-threaded programs
  • Can be used for Hashtable keys
  • Simplify state comparision

Immutability in C# can be achieved using "const" and "readonly" keywords. They are used by the C# compiler to ensure that the state of a field won’t be changed once an object is created.
The "readonly" keyword allows state modification within constructor(s) while the "const" keyword doesn’t.

No comments:

Post a Comment