Immutable collections?

Immutable collections are great, especially if your app already leverages immutable types or semantics.

.NET just shipped their first immutable collections, which I suggest you try out.


Eric Lippert has a series on Immutability in C#, and if you read it all the way through he implements a couple different immutable collections:

  1. Immutability in C# Part One: Kinds of Immutability
  2. Immutability in C# Part Two: A Simple Immutable Stack
  3. Immutability in C# Part Three: A Covariant Immutable Stack
  4. Immutability in C# Part Four: An Immutable Queue
  5. Immutability in C# Part Five: LOLZ!
  6. Immutability in C# Part Six: A Simple Binary Tree
  7. Immutability in C# Part Seven: More on Binary Trees
  8. Immutability in C# Part Eight: Even More On Binary Trees
  9. Immutability in C# Part Nine: Academic? Plus my AVL tree implementation
  10. Immutability in C# Part Ten: A double-ended queue
  11. Immutability in C# Part Eleven: A working double-ended queue

My favorite trick with collections is simply to never pass them around. If they only exist inside a single object, then making them immutable is mostly irrelevant (As long as your containing object doesn't change them then they won't change).

Usually your collection represents something, right? It's a collection of dogs or a collection of invoices...

Usually there is a thing you can do with a collection of dogs (Herd? neuter?) or a collection of invoices (pay?) There are virtually always operations that apply to the whole list of objects--operations that have functionality beyond the singular invoice.pay() (for instance, ensuring that the most important invoices are paid first), without a class around your collection, there is really no where to put those operations.

It also usually makes sense to have a few variables associated with your collection--and again without a wrapper you always end up putting those variables in some strange unnatural location.

It may seem strange at first but try it a couple times before you judge.