1

It looks like a weird design choice, because a Dictionary and an ImmutableDictionary are quite different write-wise. (Read-wise, they both implement IReadOnlyDictionary, which is fine*)

In fact, the current implementation of IDictionary<TKey, TValue>.Add() in the ImmutableDictionary class throws a NotSupportedException (see here).

So, what was the point in doing this? If a method returns an IDictionary that is in fact an ImmutableDictionary, you're going to have some troubles when adding elements in it, for instance.

*except for the name of the interface, which is subject to debate

  • 1
    Why is ImmutableDictionary<TKey, TValue> implementing IDictionary<TKey, TValue>? -- Because you can leverage an existing data structure's logic and merely forbid the disallowed operations, instead of writing a complete data structure from scratch. – Robert Harvey Jun 10 '16 at 16:21
  • 1
    @RobertHarvey at the cost of the Liskov Substitution Principle, which is worth considering. Many would argue that implementing an interface and purposely breaking parts of it is incredibly bad design. – Magus Jun 10 '16 at 20:31
  • 1
    @Magus: I can live with that, if it makes the collections easier to use and interoperable with other collections. – Robert Harvey Jun 10 '16 at 20:35
3

For the reasons why, take a read of the "Interoperating with existing collections" part of this MS blog post.

The developers of these immutable types had a choice, which I'll express here in a succinct, but somewhat loaded, way:

  1. Make them easy to use
  2. Do it properly

Originally, they went down the "do it properly" route. The IList<T> interface is a classic example of how to break the Liskov substitution principle as it positively encourages creating types that are not substitutable for each other (without checking the state of flags to determine which particular style of implementation one is handling). However, this meant they didn't interoperate nicely with existing code, nor could useful interfaces like IList<T> be used with them. So they took the decision to favour usefulness over purity. It remains a controversial decision, but was probably the correct - pragmatic - one to take.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.