How to avoid null key errors in dictionary?

19,291

Solution 1

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
}

Solution 2

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

Solution 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
Share:
19,291
eman
Author by

eman

Updated on July 27, 2022

Comments

  • eman
    eman almost 2 years

    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
    eman over 13 years
    how to check if it's null and return an empty string?
  • Bobby
    Bobby over 13 years
    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.
  • Darin Dimitrov
    Darin Dimitrov over 13 years
    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
    Darin Dimitrov over 13 years
    @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.
  • Bobby
    Bobby over 13 years
    Yes, I think that was his question, how to avoid that Exception.
  • eman
    eman over 13 years
    I don't mean in a method but in the declaration!
  • ChrisF
    ChrisF over 13 years
    @eman - I don't understand your question then. Can you update the code to show exactly what you are trying to achieve?
  • Dog Ears
    Dog Ears over 13 years
    +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
  • andreisrob
    andreisrob almost 6 years
    This answer is incorrect: TryGetValue throws an exception if the key is null.
  • Grozz
    Grozz almost 6 years
    @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: stackoverflow.com/questions/4632945/dictionary-with-null-key
  • andreisrob
    andreisrob almost 6 years
    @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.
  • Grozz
    Grozz almost 6 years
    @JasonBaley please re-read the whole question carefully, not just the caption