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.
views:
794answers:
3
+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
2009-03-03 14:42:44
+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
2009-03-03 14:42:52
+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
2009-03-03 14:44:47
Exactly why I asked this question, I felt like what I was doing was not good practice.
phsr
2009-03-03 14:46:37