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

1130-01

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;

 

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: Dew Drop – July 2, 2014 (#1807) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: