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

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

    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.

提交回复
热议问题