KeyValuePair vs. NameValueCollection
Matthew Harrington
There are other questions such as KeyValuePair vs IDictionary, but I feel this one differs slightly.
NameValueCollection takes a string key and string value.
KeyValuePair is like a dictionary, you tell it what type the key and value is.
I don't understand why NameValueCollection exists. Initializing a KeyValuePair with string types seems sufficient. I also noticed that NameValueCollection has some more methods available to it, but again why not merge both classes into one?
3 Answers
A KeyValuePair not like a dictionary. It is simply a Tuple containing the Key and the Value.
NameValueCollection is wrapper over what amounts to a IList<KeyValuePair<string,IList<string>>> (note that NameValueCollection predates generics) - operations like Get(string) are O(n) and items can be fetched by index and each Key maps to one or more Values (this differs from a Dictionary<string,string>).
A reason for this is explained in the NameValueCollection documentation:
This class can be used for headers, query strings and form data.
The newer "replacement" data-structure with some similar behavior for NameValueCollection is Lookup<string,string>. (However, it doesn't directly support the same operations as is immutable as spender notes.)
Happy coding.
1NameValueCollection existing in .NET 1.0 and 1.1, KeyValuePair is a generic type and wasn't added to .NET until 2.0. All the classes in System.Collections.Specialized all predates the addition of generics; it contains certain strongly typed (specialized if you will) for use when that's exactly what you need to users don't have to cast from object to string.
KeyValuePair is the component you use to iterate a Dictionary
var dictionary = new Dictionary<int,long>
foreach(var kvp in dictionary)
{ // kvp is KeyValuePair<int,long>. kvp.Key is the int key and kvp.Value is the long value for the key
}NameValueCollection is indexable.