#1,131 – Example of Using a Generic Dictionary

Below is an example of using a generic dictionary to count how many times each type of letter appears in a passage of text.  The keys are of type char (the letter found) and the values are of type int (# times found).

            string someText = "One cannot think well, love well, " +
                "sleep well, if one has not dined well.";

            Dictionary<char, int> charCounter = new Dictionary<char, int>();

            foreach (char c in someText)
                if (!charCounter.ContainsKey(c))
                    charCounter.Add(c, 1);
                    // charCounter[c] is of type int,
                    //   c is of type char

            Console.WriteLine("Found {0} unique characters", charCounter.Keys.Count);

            foreach (KeyValuePair<char, int> kvp in charCounter)
                Console.WriteLine("[{0}] - {1} instances", kvp.Key, kvp.Value);



#1,130 – Checking to See if a Generic Dictionary Already Contains a Key

When using a generic dictionary, you can use the square bracket syntax to retrieve the value for a specified key.  This will only work, however, if that particular key has already been added to the dictionary.  When you first create the dictionary, it contains no keys.

If you try retrieving a value for a key that doesn’t already exist in the dictionary, you’ll get a KeyNotFoundException at runtime.


You can avoid this error by first checking to the presence of a key using the ContainsKey method of the dictionary.  If this method returns true, you can safely retrieve the value of the key using the square bracket syntax.

            Dictionary<char, int> charCounter = new Dictionary<char, int>();

            int numEs = charCounter.ContainsKey('e') ? charCounter['e'] : 0;


#1,129 – Generic Dictionary Basics

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'];