How to avoid null key errors in dictionary?
How to avoid error if 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 wh开发者_高级运维at can I write in the GET to avoid error?
Thanks.
regards
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
}
You can use the Dictionary.ContainsKey
method.
So you'd write:
if (myDictionary.ContainsKey("Key2"))
{
// Do something.
}
The other alternatives are to either wrap the access in a try...catch
block or use TryGetValue
(see the examples on the MSDN page linked to).
string result = null;
if (dict.TryGetValue("Key2", out result))
{
// Do something with result
}
The TryGetMethod
is more efficient if you want do something with the result as you don't need a second call to get the value (as you would with the ContainsKey
method).
(Of course, in both methods you'd replace "Key2" with a variable.)
An 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);
}
Usage:
var dic = new Dictionary<string, string>
{
{ "key", "value" }
};
string r1 = dic.GetValue("key"); // "value"
string r2 = dic.GetValue("false"); // null
A key can never be null in a dictionary. A dictionary is a hashtable where by definition you need a non-empty key or the hash function cannot map to the corresponding element.
You're returning the wrong thing. Don't return the dictionary, pass in a 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
}
精彩评论