Search code examples
c#.netimmutability

Are immutable objects good practice?


Should I make my classes immutable where possible?

I once read the book "Effective Java" by Joshua Bloch and he recommended to make all business objects immutable for various reasons. (for example thread safety) Does this apply for C# too?

Do you try to make your objects immutable, so you have less problems when working with them? Or is it not worth the inconvenience you have to create them?


Solution

  • The immutable Eric Lippert has written a whole series of blog posts on the topic. Part one is here.

    Quoting from the earlier post that he links to:

    ASIDE: Immutable data structures are the way of the future in C#. It is much easier to reason about a data structure if you know that it will never change. Since they cannot be modified, they are automatically threadsafe. Since they cannot be modified, you can maintain a stack of past “snapshots” of the structure, and suddenly undo-redo implementations become trivial. On the down side, they do tend to chew up memory, but hey, that’s what garbage collection was invented for, so don’t sweat it.