I tried checking for null but the compiler warns that this condition will never occur. What should I be looking for?
9 Answers
Assuming you want to get the value if the key does exist, use Dictionary<TKey, TValue>.TryGetValue
:
int value;
if (dictionary.TryGetValue(key, out value))
{
// Key was in dictionary; "value" contains corresponding value
}
else
{
// Key wasn't in dictionary; "value" is now 0
}
(Using ContainsKey
and then the indexer makes it look the key up twice, which is pretty pointless.)
Note that even if you were using reference types, checking for null wouldn't work - the indexer for Dictionary<,>
will throw an exception if you request a missing key, rather than returning null. (This is a big difference between Dictionary<,>
and Hashtable
.)
-
@JonSkeet Isn't TryGetValue doing a double lookup too ([as stated in this question body](http://stackoverflow.com/questions/1413304/net-adding-dictionary-item-check-if-it-exists-or-allow-exception))? – nawfal Dec 02 '12 at 14:59
-
9@nawfal: I see no indication that that question states that at all. It says it's doing more work than `ContainsKey`, which is true, because it has to extract the value as well. It's not doing two lookups though. – Jon Skeet Dec 02 '12 at 17:56
-
Naively, I kept expecting null, but for Dictionary
, this returns the "0" equivalent in the enum. – Jess Sep 20 '15 at 20:29
The Dictionary throws a KeyNotFound
exception in the event that the dictionary does not contain your key.
As suggested, ContainsKey
is the appropriate precaution. TryGetValue
is also effective.
This allows the dictionary to store a value of null more effectively. Without it behaving this way, checking for a null result from the [] operator would indicate either a null value OR the non-existance of the input key which is no good.

- 5,282
- 1
- 34
- 47
-
Additional information can be found at MSDN: http://msdn.microsoft.com/en-gb/library/9tee9ht2.aspx – cyberzed Jan 26 '10 at 11:23
If you're just checking before trying to add a new value, use the ContainsKey
method:
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
}
If you're checking that the value exists, use the TryGetValue
method as described in Jon Skeet's answer.

- 134,786
- 31
- 255
- 325
-
2Coz you're resolving the key lookup through the hashtable twice if you immediately Get after the Contains. Wintellect PowerCollections also has `GetValueElseAdd` methods which you give a value (or a `Func
`) to also save the resolution on the Insert if you're going to add if its not there. I guess the reason that hasnt made it into the .NET libs is because the Add path is less frequent if you're using it in a cache stylee] – Ruben Bartelink Jan 26 '10 at 11:23 -
@rub: I guess that depends on the purpose of the code. If you want to use the value I agree that `TryGetValue` would be better, but if you want to check if the dictionary contains the key in order to avoid duplicate additions, I would say `ContainsKey` is just as good (if not better). – Fredrik Mörk Jan 26 '10 at 11:25
-
@Fredrik: If you *only* want to do a containment check, then yes, it's worth using ContainsKey. Note that that's not the case in the sample code of this answer. – Jon Skeet Jan 26 '10 at 11:27
-
@Jon: true, I actually missed that the added value was fetched immediately after it was added. – Fredrik Mörk Jan 26 '10 at 11:29
-
@Mork: You're right and I agree. Reason I commented is that the post doesnt make it clear that you generally want to do either ContainsKey (only) OR TryGet (Contains + Get) OR TryGet / Add (without another Get like in the code sample in the post) – Ruben Bartelink Jan 26 '10 at 11:29
-
The comments here got me to ask a question I'd long wanted to ask:- http://stackoverflow.com/questions/2139423/what-is-the-bcl-equivalent-of-getvalueelseadd-in-powercollections I guess I'll leave my comment spam here for posterity – Ruben Bartelink Jan 26 '10 at 14:22
You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.
Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);
int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
myValueLookup = myDictionay[keyToFind];
// do work...
}
else
{
// the key doesn't exist.
}

- 29,603
- 12
- 67
- 114
-
4
-
2@mookid: Not in my opinion. The idea is to try to look up the key, and take one course of action if it's found, and another course of action otherwise, right? – Jon Skeet Jan 26 '10 at 11:26
-
4@Jon - Honestly? Because I didn't know about `TryGetValue`. Thankfully, I do now, so I'll know in future. I'm going to leave this answer intact, though 'cos discussion is valuable. – ZombieSheep Jan 26 '10 at 11:49
-
@JonSkeet Because before C# 7, you couldn't use `TryGetValue` in a lambda expression. Though that does make me think a new extension to C# would be a `catch` operator similar to the `null` coalescing operator. – NetMage Aug 15 '17 at 21:51
-
@NetMage: You could do it in a lambda expression - just not an expression-bodied lambda expression. – Jon Skeet Aug 15 '17 at 21:52
A helper class is handy:
public static class DictionaryHelper
{
public static TVal Get<TKey, TVal>(this Dictionary<TKey, TVal> dictionary, TKey key, TVal defaultVal = default(TVal))
{
TVal val;
if( dictionary.TryGetValue(key, out val) )
{
return val;
}
return defaultVal;
}
}

- 3,001
- 4
- 31
- 54
-
Sometimes I wonder why this isnt added to the standard library. Nearly all languages that use hashmaps return null if there is no entry, not a freaking exception. An item not existing in your dictionary is not exceptional behavior. – Adam Hess Sep 05 '19 at 17:02
-
@AdamHess - that's why you have Hashtable() in c#... unfortunately, your keys get boxed there... :( – veljkoz Oct 25 '19 at 12:02
Consider the option of encapsulating this particular dictionary and provide a method to return the value for that key:
public static class NumbersAdapter
{
private static readonly Dictionary<string, string> Mapping = new Dictionary<string, string>
{
["1"] = "One",
["2"] = "Two",
["3"] = "Three"
};
public static string GetValue(string key)
{
return Mapping.ContainsKey(key) ? Mapping[key] : key;
}
}
Then you can manage the behaviour of this dictionary.
For example here: if the dictionary doesn't have the key, it returns key that you pass by parameter.

- 143
- 1
- 9
You should probably use:
if(myDictionary.ContainsKey(someInt))
{
// do something
}
The reason why you can't check for null is that the key here is a value type.

- 30,834
- 11
- 63
- 78
-
1The type of the value is somewhat irrelevant, as checking for null wouldn't have the desired effect. – Jon Skeet Jan 26 '10 at 11:24
-
@Johannes, Jon's solution is of course way better, but the asker did state that he checked if the key exists, and it is a Dictionary
, so the key is also a value type here. – Razzie Jan 26 '10 at 13:03
int result= YourDictionaryName.TryGetValue(key, out int value) ? YourDictionaryName[key] : 0;
If the key is present in the dictionary, it returns the value of the key otherwise it returns 0.
Hope, this code helps you.

- 1,281
- 17
- 22
-
5If the key exists, this code will lookitup twice. `TryGetValue` is enough, use `value` instead of `result` – Mathieu VIALES Nov 26 '19 at 16:56
-
1@MathieuVIALES should this be YourDictionaryName.TryGetValue(key, out int value) ? value : 0; instead? – user989988 Aug 18 '22 at 19:10