Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

dictionary

People also ask

What's going to happen to Celsius?

April 12, 2022: Celsius Network shows its first sign of distress by announcing its U.S. platform will begin holding non-accredited investors' coins in custody, where investors will no longer be able to add new assets and earn rewards on Celsius' Earn platform.

How did Celsius crash?

The company was caught in the chain reaction rippling across crypto markets following selloffs in digital currencies this year, and it froze withdrawals, swaps, and transfers last month. Founded in 2017 by entrepreneur Alex Mashinsky, Celsius was valued at more than $3 billion last fall in its latest venture round.

Is Celsius collapsing?

Celsius Network (CEL) announced on July 13 that it filed for Chapter 11 bankruptcy after a month of turmoil. The embattled crypto lender made headlines last month after freezing customer accounts, citing “extreme market conditions.”

What is Celsius medium?

Celsius is a loan and borrowing platform that has been operational since 2017. On the Celsius platform, customers have the option to earn income on their crypto assets by storing them there, or to use them as collateral for loans.


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


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.


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.


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

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