The dictionary throws an exception even after checking for null

I am trying to read the key value from a dictionary as follows:

if (myDic["myKey"] != null) { } 

I see that I am checking for null, but even then it throws a KeyNotFoundException. How else should I check this out? Please advise!

+4
source share
8 answers

It looks like you are HashTable behavior of HashTable with the behavior of Dictionary<TKey, TValue> . The HashTable class returns null when the key is absent, and Dictionary<TKey, TValue> throws an exception.

To avoid this problem, you need to either use ContainsKey or TryGetValue .

 object value; if (myDic.TryGetValue("apple", out value)) { ... } 
+10
source

using

 if(mydic.ContainsKey("myKey")) 
+6
source

It throws an exception because you are trying to get the value of this element (checking if the value is null), but the value cannot be restored because the key does not exist.

using:

 if (myDic.ContainsKey("myKey")) { } 

or

 if (myDic.TryGetValue("myKey", out value)) { } 
+3
source

Using:

 if (myDic.ContainsKey("myKey")) { } 
+1
source

You check if the value associated with the apple key is not null if the dictionary contains the apple key. For this you would like to use:

 if( myDic.ContainsKey("apple") ) { } 
+1
source

Here you should use Contains or TryGetValue.

 if (myDic.ContainsKey) { // get value out of dictionary var myValue = myDic["myKey"]; } 

or

 string myValue; if (myDic.TryGetValue("myKey", out myValue) { // do something with myValue } 

[the example above assumed that your dictionary has type string values, but it could be anything]

The advantage of the second approach is that you can check if an element exists in the dictionary and get its value as a single atomic operation, instead of doing the Contains check first and then a second call to get the value.

0
source

Perhaps the most concise way to do this is to:

 SomeType myVal; if(myDic.TryGetValue("myKey",out myVal)) { //good to go } 
0
source

Source: https://habr.com/ru/post/1345588/


All Articles