I am trying to read a value of a key from a dictionary like the following :
if (myDic["myKey"] != null)
{
}
I can see that I am checking for null, but even then it throws KeyNotFoundException. How else should I check this? Please advise!
It looks like you're confusing the behavior of HashTable
with that of Dictionary<TKey, TValue>
. The HashTable
class will return a null
value when the key is not present while Dictionary<TKey, TValue>
will throw an exception.
You need to either use ContainsKey
or TryGetValue
to avoid this problem.
object value;
if (myDic.TryGetValue("apple", out value)) {
...
}
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