Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 what can I write in the GET to avoid error?

Thanks.

regards

like image 388
eman Avatar asked Nov 03 '10 10:11

eman


2 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
}
like image 130
Grozz Avatar answered Nov 03 '22 17:11

Grozz


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.)

like image 29
ChrisF Avatar answered Nov 03 '22 15:11

ChrisF