8

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

eman
  • 217
  • 2
  • 4
  • 9

5 Answers5

16

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
}
Grozz
  • 8,317
  • 4
  • 38
  • 53
  • 1
    +1Use the try method, Don't use the contains method if you want to retrieve the value, it'll be inefficient as you'll effectively do the lookup twice – Dog Ears Nov 04 '10 at 07:28
  • 12
    This answer is incorrect: `TryGetValue` throws an exception if the key is null. – andreisrob May 31 '18 at 16:48
  • @JasonBaley not sure this has anything to do with the answer, `Dictionary` doesn't support null keys. Additional discussion can be found in this thread: https://stackoverflow.com/questions/4632945/dictionary-with-null-key – Grozz Jun 01 '18 at 13:34
  • 2
    @Grozz The question was how to avoid getting an error when a null key is provided for lookup in a dictionary. Passing a null key to `TryGetValue` will still throw an error, so it doesn't answer the question. In your answer, if `key` is null, an exception is thrown, so how does this address the original question? He's trying to avoid the exception. – andreisrob Jun 01 '18 at 17:28
  • @JasonBaley please re-read the whole question carefully, not just the caption – Grozz Jun 04 '18 at 11:38
13

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

ChrisF
  • 134,786
  • 31
  • 255
  • 325
3

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
abatishchev
  • 98,240
  • 88
  • 296
  • 433
0

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • how to check if it's null and return an empty string? – eman Nov 03 '10 at 10:20
  • I think that was his question, how to avoid that a `null` gets set as key...though, his code does not quiet fit that assumption. – Bobby Nov 03 '10 at 10:21
  • In your code you never access the dictionary by key. You simply return a static dictionary. I don't understand what do you mean. – Darin Dimitrov Nov 03 '10 at 10:21
  • @Bobby, this can never happen. If you try to use null as a key in a dictionary you will get ArgumentNullException so you can never have a dictionary with null key. – Darin Dimitrov Nov 03 '10 at 10:22
  • Yes, I think that was his question, how to avoid that Exception. – Bobby Nov 03 '10 at 10:35
0

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
}
DanDan
  • 10,462
  • 8
  • 53
  • 69