#1,129 – Generic Dictionary Basics
July 1, 2014 1 Comment
The generic dictionary class, System.Collections.Generic.Dictionary<TKey,TValue>, allows you to store a collection of key/value pairs, where the both the keys and the values have a particular type.
You specify types for the keys and values when you declare an instance of the dictionary, creating a constructed type. The example below creates an instance of a dictionary that stores an integer value for each of a set of character values.
Dictionary<char, int> charCounter = new Dictionary<char, int>();
By default, the collection contains no entries–no key/value pairs. You add an entry using the Add method, specifying a new key to be added, along with its value. Note that the key is of type char and the value is of type int.
charCounter.Add('x', 12);
If a dictionary already contains a particular key, you can retrieve the value using square bracket syntax.
int numXs = charCounter['x'];