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

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

    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 Mapping = new Dictionary
        {
            ["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.

提交回复
热议问题