5

The .NET type SortedDictionary<TKey, TValue> does not implement the interface IReadOnlyDictionary<TKey, TValue>, although Dictionary<TKey, TValue> does.

It is trivial to make SortedDictionary implement IReadOnlyDictionary by subclassing it (< 10 LOCs).

But I guess there are good reasons why the framework developers did not do it and that’s why I shouldn’t do it. What are those reasons?

5
  • Just a guess, though maybe SortedDictionary optimizes sorting by sorting only upon retrieving data, so you can insert many values without sorting each time. However in doing so, reading a value is actually changing the dictionary's state, hence it isn't read only. This is just my idea, so I won't post it as a solution.
    – Neil
    Commented Sep 22, 2014 at 8:52
  • 2
    I guess they simply forgot to add it, or considered it too much work for too little gain. Commented Sep 22, 2014 at 8:58
  • @Neil: Good idea! However, they are using red-black trees, and the code does not seem to modify the collection. Moreover, the docs says about thread safety: “A SortedDictionary<TKey, TValue> can support multiple readers concurrently, as long as the collection is not modified.” So I think that’s not the reason.
    – Martin
    Commented Sep 22, 2014 at 9:04
  • @Martin It's reasonable to assume there is some detail like that going on though. Otherwise I can't see why they wouldn't make SortedDictionary implement IReadOnlyDictionary.
    – Neil
    Commented Sep 22, 2014 at 9:51
  • Hmmm. Also looks like SortedList doesn't support IReadOnlyList.
    – J Trana
    Commented Sep 24, 2014 at 1:58

1 Answer 1

4

Looking at MSDN today, one can see that the MSDN documentation page for SortedDictionary<TKey, TValue>, SortedDictionary<TKey, TValue> does implement IReadOnlyDictionary<TKey, TValue>.

According to the internet archive, that was not the case on November 14th, 2013.

Given that information, it is likely that it was simply an oversight from Microsoft, fixed in a recent .NET point update.

1
  • Indeed. The MSDN page mentions “.NET 4.5.3”, and today, sourceof.net shows 4.5.2, where IReadOnlyDictionary is not implemented.
    – Martin
    Commented Dec 2, 2014 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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