I tried checking for null but the compiler warns that this condition will never occur. What should I be looking for?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
If you're just checking before trying to add a new value, use the
ContainsKey
method:If you're checking that the value exists, use the
TryGetValue
method as described in Jon Skeet's answer.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.
Consider the option of encapsulating this particular dictionary and provide a method to return the value for that 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.