The System.Collections.Specialized namespace contains a series of collections that either are strongly typed or offer functionality that is not widely required.
The strongly typed collections all deal exclusively with strings.
The NameObjectCollectionBase class is an abstract class that is based on a Hashtable but that accepts only strings as key types. The only concrete implementation of this class in the collections namespace is NameValueCollection. The NameValueCollection class is derived from NameObjectCollectionBase but can be used to store multiple values for each key. However, both the key and the values must be strings. The most obvious use of this class is processing HTTP headers. Here’s an example:
NameValueCollection x_collection = new NameValueCollection(); x_collection.Add("key", "value1"); x_collection.Add("key", "value2"); string[] x_arr = x_collection.GetValues("key"); foreach (string x_str in x_arr) { Console.WriteLine("VALUE: " + x_str); }
The result of this fragment follows:
VALUE: value1 VALUE: value2
The StringCollection class represents an implementation of the IList interface such that the interface handles only strings.
The following two collections have characteristics that make them useful in specific circumstances but not as everyday collections.
The ListDictionary class implements the IDictionary interface using a single-linked array. It behaves like a Hashtable, which implements the same interface, but is faster when dealing with up to ten items. This is based on the premise that iterating over a small array is faster than computing hash codes. For more than ten items, the iteration takes longer than hashing and the benefits of this class are negated; a Hashtable will offer better performance
The HybridDictionary class provides the best of both a ListDictionary and a Hashtable. If the number of elements in the collection is small, they are maintained in a ListDictionary. Once the number goes above what’s optimal for a ListDictionary, they are automatically transferred to a Hashtable for better performance. This results in a one-off performance hit. If the number of elements falls below the ListDictionary threshold, they remain in the Hashtable.