How to avoid errors in a key key in the dictionary?

How to avoid an error if the key is null?

//Getter/setter public static Dictionary<string, string> Dictionary { get { return Global.dictionary; } set { Global.dictionary = value; } } 

UPDATE:

 Dictionary.Add("Key1", "Text1"); Dictionary["Key2"] <-error! so what can I write in the GET to avoid error? 

Thanks.

considers

+6
c # static-methods
source share
5 answers

Use TryGetValue :

 Dictionary<int, string> dict = ...; string value; if (dict.TryGetValue(key, out value)) { // value found return value; } else { // value not found, return what you want } 
+15
source share

You can use the Dictionary.ContainsKey method.

So you should write:

 if (myDictionary.ContainsKey("Key2")) { // Do something. } 

Other alternatives are to either wrap access in a try...catch , or use TryGetValue (see the examples on the MSDN page associated with).

 string result = null; if (dict.TryGetValue("Key2", out result)) { // Do something with result } 

TryGetMethod more efficient if you want to do something with the result, since you do not need a second call to get the value (as with the ContainsKey method).

(Of course, in both methods you would replace "Key2" with a variable.)

+10
source share

Extension Method:

 public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key) { TValue result; return dic.TryGetValue(key, out result) ? result : default(TValue); } 

Using:

 var dic = new Dictionary<string, string> { { "key", "value" } }; string r1 = dic.GetValue("key"); // "value" string r2 = dic.GetValue("false"); // null 
+2
source share

A key can never be null in a dictionary. A dictionary is a hash table where, by definition, you need a non-empty key or a hash function cannot be matched to the corresponding element.

0
source share

You come back wrong. Do not return the dictionary, skip the key and return the value.

 public static string GetValue(string key) { if(Global.dictionary.ContainsKey(key)) { return Global.dictionary[key]; } return ""; // or some other value } 
0
source share

All Articles