I have a scenario where there is a dictionary that might or might not have a key value at a given time. I am presently testing to see if the value exists in the following manner
Here is an example for you
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, string> test = new Dictionary<string, string>();
test.Add("one", "value");
//
// Use TryGetValue to avoid KeyNotFoundException.
//
string value;
if (test.TryGetValue("two", out value))
{
Console.WriteLine("Found");
}
else
{
Console.WriteLine("Not found");
}
}
}
If you are talking about the generic dictionary, then the best way to avoid the exception is to use the ContainsKey method to test if the dictionary has a key before using it.
Take a look at the dictionary's TryGetValue method
int myInt;
if (!_myDictionary.TryGetValue(key, out myInt))
{
myInt = 0;
}
A couple of people have suggested using ContainsKey. This is not a good idea if you actually want the value because it will mean 2 lookups - e.g.
if (_myDictionary.ContainsKey(key)) // look up 1
{
myInt = _myDictionary[key]; // look up 2
}
First of all, using try catch
is not a good idea here, you are unnecessarily slowing down the code where you can easily accomplish that with ContainsKey
or TryGetValue
I would propose the solution with TryGetValue
as mentioned here - https://msdn.microsoft.com/en-us/library/kw5aaea4(v=vs.110).aspx (check the examples)
But you can optimize more. The line myInt = 0;
is redundant as @Mark suggested. TyGetValue
automatically puts the default
value ( 0
for int
) when it returns.
If the key is not found, then the value parameter gets the appropriate default value for the type TValue; for example, 0 (zero) for integer types, false for Boolean types, and null for reference types. https://msdn.microsoft.com/en-us/library/bb347013%28v=vs.110%29.aspx
So the final code could be
int myInt;
if (_myDictionary.TryGetValue(key, out myInt))
{
[...] //codes that uses the value
}else{
[...] //codes that does not use the value
}
Or -
int myInt;
_myDictionary.TryGetValue(key, out myInt))
[...] //other codes.
The next paragraph is copied from the documentation ot TryGetValue-
This method combines the functionality of the ContainsKey method and the Item property. If the key is not found, then the value parameter gets the appropriate default value for the type TValue; for example, 0 (zero) for integer types, false for Boolean types, and null for reference types. Use the TryGetValue method if your code frequently attempts to access keys that are not in the dictionary. Using this method is more efficient than catching the KeyNotFoundException thrown by the Item property. This method approaches an O(1) operation.
BTW, ContainsKey
and TryGetValue
both has running time O(1). So, it does not matter much, you can use any.