6

I noticed that Dictionary Class implements IDictionary<TKey, TValue> as well as IReadOnlyDictionary<TKey, TValue>.

However IDictionary Interface does not implement IReadOnlyDictionary<TKey, TValue>.

This means that if my class has an IDictionary<TKey, TValue>, and I need to pass an IReadOnlyDictionary<TKey, TValue> I ought to create an adapter for this, or use a different work around.

IMHO every class that has the functionality of an IDictionary<TKey, TValue> also has the functionality of an IReadOnlyDictionary<TKey, TValue>.

Did they simply forget to implement it, or are there really meaningful classes that implement IDictionary<TKey, TValue> that can't have a meaningful implementations of IReadOnlyDictionary<TKey, TValue>?

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • 5
    Shortly - for backward compatibility. `IReadOnlyXyz` interfaces are introduced later, so making the existing interfaces "inherit" from them (even if it's possible) would be a breaking change. – Ivan Stoev Jul 24 '17 at 09:08
  • Would it be a breaking change if IReadOnlyDictionary was implemented explicitly? – Harald Coppoolse Jul 24 '17 at 09:34
  • 1
    @HaraldCoppoolse - There's no implementation on an interface so it can't be implemented, explicitly or implicitly. – Enigmativity Jul 24 '17 at 09:46
  • You don't need an adapter, you can use a simple cast: ` private IDictionary _Dictionary= new Dictionary(); ` ` public IReadOnlyDictionary TheDictionary => (IReadOnlyDictionary)_Dictionary; ` – Bernhard Hiller Jul 24 '17 at 14:01
  • 2
    Bernhard: your examle works because in your excample the actual object that _Dictionary refers to also implements `IReadOnlyDictionary`. However, if I get an object of a class that implements `IDictionary`, I can't be certain that the object also implements the `IReadOnlyDictionary`. If it doesn't, I get an `InvalidCastException` when trying to cast. For those situations I still need an adapter – Harald Coppoolse Aug 09 '17 at 06:47

0 Answers0