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

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

    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.

提交回复
热议问题