2

I'm trying to wrap my head around why the IDictioary<TKey, TValue>.Values property is of type ICollection<TValue> as opposed to IEnumerable<TValue>. The .NET implementation of the Values property implements the interface property explicitly and then exposes the Values property as type Dictionary<TKey, TValue>.ValueCollection which throws an exception when you try to add or remove values from it.

This seems like a complete hack. Because of the nature of a dictionary, does it ever make sense to create an implementation which allows you get get a collection of the values in the dictionary and add / remove values from it?

Anthony
  • 9,451
  • 9
  • 45
  • 72
  • http://programmers.stackexchange.com/questions/118451/difference-between-various-collection-generic-interfaces-in-c – Levi Botelho Oct 31 '12 at 19:22

1 Answers1

6

This allows you to use the Count property and the Contains() method on a dictionary interface.

You're right; it is an ugly hack.
The ideal soltuion would have been to use the new (to .Net 4.5) IReadOnlyCollection<T> interface.

Servy
  • 202,030
  • 26
  • 332
  • 449
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • +1: Furthermore, you wouldn't want to allow `Add` & `Remove` methods on the value collection because the Key would be null. – IAbstract Oct 31 '12 at 19:22
  • Why should the value collection have a `Contains` method? `Count` is the only one that makes sense to me. – Servy Oct 31 '12 at 19:23
  • +1: It should have been `IReadOnlyCollection`, but it didn't exist at the time, and now they're stuck. – Cole Cameron Oct 31 '12 at 19:23
  • Just for fun, can you think of a Dictionary implementation which may benefit from being able to add/remove Keys/Values independently from the dictionary itself like the current interface technically supports? – Anthony Oct 31 '12 at 19:26
  • Well, `ICollection` has a property [`IsReadOnly`](http://msdn.microsoft.com/en-us/library/0cfatk9t.aspx) for that – Paolo Moretti Oct 31 '12 at 19:27
  • Do you check `IsReadOnly` before you add to any ICollection (as in, any list, or collection, etc)? If something's read only, why bother having methods that imply otherwise? Hence, `IReadOnlyCollection`. It was long overdue. – Cole Cameron Oct 31 '12 at 19:29
  • @ColeCameron Tecnically you should. Anyway, I agree that `IReadOnlyCollection<>` is more suitable. – Paolo Moretti Oct 31 '12 at 19:36