What happens to C# Dictionary<int, int> lookup if the key does not exist?

c#, dictionary

Solution

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

Problem

I tried checking for null but the compiler warns that this condition will never occur. What should I be looking for?

Original source

Related problems