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.
The Dictionary throws a KeyNotFound exception in the event that the dictionary does not contain your key. As suggested, ContainsKey is the appropriate precaution. TryGetValue is also effective. This allows the dictionary to store a value of null more effectively.
A KeyNotFoundException is thrown when an operation attempts to retrieve an element from a collection using a key that does not exist in that collection. KeyNotFoundException uses the HRESULT COR_E_KEYNOTFOUND, which has the value 0x80131577.
"The given key was not present in the dictionary." A better way would be: "The given key '" + key.
Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.
Use Dictionary.TryGetValue
instead:
Dictionary<int,string> dictionary = new Dictionary<int,string>(); int key = 0; dictionary[key] = "Yes"; string value; if (dictionary.TryGetValue(key, out value)) { Console.WriteLine("Fetched value: {0}", value); } else { Console.WriteLine("No such key: {0}", key); }
Try using: Dict.ContainsKey
Edit:
Performance wise i think Dictionary.TryGetValue
is better as some other suggested but i don't like to use Out when i don't have to so in my opinion ContainsKey is more readable but requires more lines of code if you need the value also.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With