by kirupa |
13 October 2006In the
previous page
you learned the basic syntax for using a dictionary. In this
page, I will explain how to avoid some roadblocks you may
encounter during their use.
You may run into situations where the
key you enter cannot be found by the dictionary. Unlike similar
data structures where accessing data that doesn't
exist results in a silent failure, you have to be
careful of ensuring that the key you pass actually exists in
your Dictionary object. If you pass in a value that does not
exist, a KeyNotFoundException will be thrown:
In any application, the above
error will crash the program. Therefore, it is best to
recognize these errors and prevent them from causing damage.
There are two ways you can do that:
-
Checking if the key exists in the
Dictionary prior to accessing the value.
-
Using a try/catch block to catch the
exception.
Let me explain the above two methods in
greater detail.
To check if a value exists, you can use the Dictionary's
containsKey method to return a true if the key exists
or a false if the key does not exist:
- //Using containsKey()
- if
(coffeeStat.ContainsKey("Kirupa"))
{
- Console.WriteLine("Value
is: " +
coffeeStat["Kirupa"]);
- }
In the above example, if our coffeeStat
dictionary object contains the key "Kirupa", the value will
be displayed in the console.
In the above approach, you check whether a key exists before
performing any operation on the dictionary involving the
key. Another approach is to pass the key to your dictionary
object and deal with the consequences later. That is where
the try/catch statement comes in handy:
- try
- {
- Console.WriteLine("Value
is: " +
coffeeStat["Kirupa"]);
- }
- catch
(KeyNotFoundException
e)
- {
- Console.WriteLine(e.Message);
- }
In the above piece of code, you always pass
"Kirupa" into the coffeeStat dictionary, and only if there
is an error (a KeyNotFoundException), will the catch
statement become active and execute any code contained
within it.
Regardless of which approach you employ to check whether a
key exists in a dictionary, you will ensure that your
application does not crash. There are some performance
implications with catching exceptions over containsKey, but
we will not worry about that in this tutorial. Generally,
catching exceptions is a bit slower than using containsKey.
Onwards to the
next page!
|