Wednesday, December 22, 2010

KeyValuePair vs Dictionary

KeyValuePair or Dictionary for a method that should return a collection of key and values?

Apparently KeyValuePair isn't really intended to be used on its own outside of a Dictionary.

If we look at the signature of both types we'll find that


public struct KeyValuePair <TKey, TValue>
{
}


and for Dictionary:


public class Dictionary<TKey, TValue> : ... IEnumerable<KeyValuePair<TKey, TValue>> ...
{
}


so it's not a matter of KeyValuePair vs Dictionary but really IEnumerable<KeyValuePair<TKey, TValue>> vs Dictionary<TKey, TValue> and
since a dictionary is an IEnumerable<KeyValuePair<TKey, TValue>> then the answer is easy: use a dictionary.

No comments: