Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Dictionary<TKey, TValue> not have a Add method that takes a KeyValuePair object?

According to the .NET API, the class Dictionary<TKey, TValue> is inherited from ICollection<T>, where T is KeyValuePair<TKey, TValue>. How does the Dictionary<TKey, TValue> class hide some of the methods it inherits from ICollection<T>?

For example:

ICollection<T> has the method ICollection.Add(T item) but when you use a Dictionary<TKey, TValue> object it doesn't have that method. You can only use Dictionary<TKey, TValue>.Add(TKey key, TValue value). There is no Dictionary<TKey, TValue>.Add(KeyValuePair<TKey,TValue> kvp) method.

Anyone know why? How are those methods hidden?

like image 907
LamdaComplex Avatar asked Dec 12 '22 10:12

LamdaComplex


2 Answers

That is done by implementing the Interface explicitly and making this implementation private/protected... see

  • How to hide some members of an interface
  • http://www.iridescence.no/post/HidingInterfaceMembers.aspx

You could always cast the Dictionary to ICollection and then call Add - though I wouldn't do this because I don't know whether it would work...

like image 59
Yahia Avatar answered Dec 14 '22 23:12

Yahia


They're "hidden" use explicit interface implementation. So you can use:

ICollection<KeyValuePair<Foo, Bar>> collection = dictionary;
collection.Add(...);

According to the documentation that should work... although usually it would be simply to use an alternative approach.

like image 38
Jon Skeet Avatar answered Dec 14 '22 22:12

Jon Skeet