tags:

views:

794

answers:

3

I am using a dictionary to perform lookups for a program I am working on. I run a bunch of keys through the dictionary, and I expect some keys to not have a value. I catch the KeyNotFoundException right where it occurs, and absorb it. All other exceptions will propagate to the top. Is this the best way to handle this? Or should I use a different lookup? The dictionary uses an int as its key, and a custom class as its value.

+6  A: 

Dict.ContainsKey ? :)

Edit:
Performance wise i think "Dictionary.TryGetValue" is better as some other suggested but i dont like to use Out when i dont have to so in my opinion ContainsKey is more readable.

Petoj
+6  A: 

Use Dictionary.TryGetValue instead:

Dictionary<int,string> dictionary = new Dictionary<int,string>();
dictionary[0] = "Yes";

string value;
if (dictionary.TryGetValue(0, out value))
{
    Console.WriteLine("Fetched value: {0}", value);
}
else
{
    Console.WriteLine("No such key", value);
}
Jon Skeet
+1  A: 

you should use the 'ContainsKey(string key)' method of the Dictionary to check if a key exists. using exceptions for normal program flow is not considered a good practice.

Remco Ros
Exactly why I asked this question, I felt like what I was doing was not good practice.
phsr