Immutable Collections


I just saw an interesting post that talks about a general pattern of immutable reference types. Good read. I highly recommend it!


At the end of the post the author suggests that we add “value object” generic collection to the BCL. It’s an interesting suggestion, but unfortunately not as easy as it may seem. The difficulty lays in the fact that the items in such collection also need to be immutable. String is an immutable collection of characters, which are immutable themselves.


One way to design this would be to add IImmutable marker interface, implement it on immutable types, and constrain the proposed ReadOnlyList<TImmutable> to TImmutable : IImuttable. Now, I am not sure the value of doing this outweighs the added complexity, but we will take a closer look.

Comments (4)

  1. TAG says:

    Having immutable objects like this without support from runtime / language is stupid.

    The best that MS can do is to provide developer way to write two methods that will do same thing but with different result.

    One function must mutate existing object in cheapest way, another one is to create new immuntable object with new properties.

    Runtime (or language) must select opropriate methods for execution – but for end-user developer it must looks like all objects are immutable !

  2. Mark says:

    Not to mention that there is no way to enforce the contract that such a marker interface would attempt to imply, which would make it useless if deep in your object you’ve got a falsely-marked class. Seems like an interesting thing to do would be to examine TImmutable for members that cause mutations. Perhaps at runtime through a naive "look for property setters through reflection" approach, or have the compiler mark the type using some stronger code analysis (looking for stfld instructions outside the constructor seems like a straighforward approach)

  3. Krzysztof Cwalina says:

    Yes, the easiest thing would be not to have a built-in enforcement of the contract. The interface would be just an indication to the developer (through the constraint) that they are using the collection properly.

    I can imagine the verifier checking the contract (as you described by looking for store instructions), but that raises the complexity of the feature even more.

  4. Tanveer Badar says:

    Oh dear! TAG you are wishing const modifier (C++) on member functions.