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 what 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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With