3

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 NewSupportedException.

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
    So the documentation is just plain wrong? https://msdn.microsoft.com/en-us/library/dn455946(v=vs.111).aspx – paparazzo Jun 10 '16 at 14:17
  • I suspect it's so that the `ImmutableDictionary` can be easily dropped into code without people having to worry they're calling methods that take `IDictionary` even though it doesn't mutate the dictionary. Otherwise they'd have to make more changes. It's not ideal, but it's (slightly) pragmatic! – Sean Jun 10 '16 at 14:21
  • @Paparazzi Indeed, the documentation link you give is wrong, decompilation shows the an exception is thrown. See https://github.com/dotnet/corefx/blob/21fd3b96ff8c470cb4f98c316821060c8ef25944/src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs – Vincent Ripoll Jun 10 '16 at 15:10
  • @Sean: the trouble is that in code that uses the IDictionary<,>.Add() method, an exception will be thrown if you change the concrete underlying object to an ImmutableDictionary, so you'll have some worries at runtime. – Vincent Ripoll Jun 10 '16 at 15:12
  • @VincentRipoll - that's right. But passing something you know is an `ImmutableDictionary` to a method that tries to add to the dictionary probably isn't a good idea, either. – Sean Jun 10 '16 at 15:19
  • IReadOnlyDictionary was not an interface that they *liked* to add. But they had to in .NET 4.5, it was necessary to implement the language projection that makes WinRT work, it projects IMapView. Whether the project was started too soon or they followed the design rule that dictionaries should implement IDictionary is something you'll have to ask the designers. – Hans Passant Jun 10 '16 at 15:41

0 Answers0