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!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It looks like you’re confusing the behavior of
HashTablewith that ofDictionary<TKey, TValue>. TheHashTableclass will return anullvalue when the key is not present whileDictionary<TKey, TValue>will throw an exception.You need to either use
ContainsKeyorTryGetValueto avoid this problem.