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

前端 未结 9 1233
感情败类
感情败类 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:42

    A helper class is handy:

    public static class DictionaryHelper
    {
        public static TVal Get(this Dictionary dictionary, TKey key, TVal defaultVal = default(TVal))
        {
            TVal val;
            if( dictionary.TryGetValue(key, out val) )
            {
                return val;
            }
            return defaultVal;
        }
    }
    

提交回复
热议问题