What type should myCustomDictionary.Values โ€‹โ€‹return?

If you have a Dictionary<k, v> myDictionary , then myDictionary.Values will be of type Dictionary<k, v>.ValueCollection , and myDictionary.Keys will be of type Dictionary<k, v>.KeyCollection .

I do not understand why the type myDictionary.Values not like IEnumerable<v> , IList<v> or anything else.

Now, with that in mind, if I create a custom dictionary type; Dictionary2<k1, k2, v> , should myCustomDictionary.Values return an IEnumerable<v> or a custom ValueCollection tool? More importantly, why?

+7
source share
2 answers

Note that Dictionary<TKey, TValue>.ValueCollection really implements ICollection<TValue> and therefore also IEnumerable<TValue> .

The reason the property is typed as possible for performance reasons: since the methods of this class are not virtual, they can be explicitly resolved at JIT compilation time, instead of requiring a vtable search for each method call at runtime. effectively removes one level of indirection from each method that you call in the collection. (It also gives JIT the ability to embed these method calls!)

Of course, you can implicitly convert the object to ICollection<TValue> if necessary, so there is no loss of functionality, just a bit of (micro) optimization.

In your case, there is no reason why you cannot return an ICollection<TValue> , but you can return a more specific type if you want. If you do this, you will need to explicitly implement the interface property IDictionary<TKey, TValue>.Values to satisfy the interface:

 private ValueCollection valueCollection; public ValueCollection Values { get { return valueCollection; } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return valueCollection; } } 

This correctly means that any performance advantage will be provided only to consumers of this class if they use the link entered as the type of your collection; there will be no performance advantage if they take a link to IDictionary<TKey, TValue> , as they will be forced to choose, but to access your collection of values โ€‹โ€‹via ICollection<TValue> anyway.

In my work, I did not find that the performance difference is significant enough to guarantee the return of anything more specific than ICollection<TValue> . Remember: always be guided and never prematurely optimize.

+5
source

Dictionary<k, v>.ValueCollection implements IEnumerable<v> and Dictionary<k, v>.KeyCollection implements IEnumerable<k> . This is not like returning results that are not listed.

By returning an actual class that implements IEnumerable instead of introducing the result as IEnumerable , they have the option to include some extra functionality. For example, both collections have the Count property, which is not easily accessible from any IEnumerable .

+1
source

All Articles