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

C#Dictionary

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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.

Solution 3 - C#

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.

Solution 4 - C#

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

Solution 5 - C#

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;
    }
}

Solution 6 - C#

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.

Solution 7 - C#

ContainsKey is what you're looking for.

Solution 8 - C#

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.

Solution 9 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondeltanovemberView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#antikView Answer on Stackoverflow
Solution 3 - C#ChrisFView Answer on Stackoverflow
Solution 4 - C#ZombieSheepView Answer on Stackoverflow
Solution 5 - C#sheamusView Answer on Stackoverflow
Solution 6 - C#pablocom96View Answer on Stackoverflow
Solution 7 - C#user1228View Answer on Stackoverflow
Solution 8 - C#RazzieView Answer on Stackoverflow
Solution 9 - C#Nitika ChopraView Answer on Stackoverflow