What happens to C# Dictionary lookup if the key does not exist?

前端 未结 9 1211
感情败类
感情败类 2021-02-01 00:09

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

9条回答
  •  一生所求
    2021-02-01 00:35

    You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.

    Dictionary myDictionary = new Dictionary();
    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.
    }
    

提交回复
热议问题