Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary throws exception even after checked for null

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!

like image 866
saikamesh Avatar asked Nov 29 '22 17:11

saikamesh


1 Answers

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)) {
  ...
}
like image 97
JaredPar Avatar answered Dec 04 '22 23:12

JaredPar