#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;