Testing for Dictionary KeyNotFoundException

后端 未结 4 654
猫巷女王i
猫巷女王i 2021-01-26 09:51

I have a scenario where there is a dictionary that might or might not have a key value at a given time. I am presently testing to see if the value exists in the following manner

4条回答
  •  野性不改
    2021-01-26 10:42

    First of all, using try catch is not a good idea here, you are unnecessarily slowing down the code where you can easily accomplish that with ContainsKey or TryGetValue

    I would propose the solution with TryGetValue as mentioned here - https://msdn.microsoft.com/en-us/library/kw5aaea4(v=vs.110).aspx (check the examples)

    But you can optimize more. The line myInt = 0; is redundant as @Mark suggested. TyGetValue automatically puts the default value ( 0 for int) when it returns.

    If the key is not found, then the value parameter gets the appropriate default value for the type TValue; for example, 0 (zero) for integer types, false for Boolean types, and null for reference types. https://msdn.microsoft.com/en-us/library/bb347013%28v=vs.110%29.aspx

    So the final code could be

    int myInt;
    if (_myDictionary.TryGetValue(key, out myInt))
    {
        [...] //codes that uses the value
    }else{
        [...] //codes that does not use the value
    }
    

    Or -

    int myInt;
    _myDictionary.TryGetValue(key, out myInt))
    [...] //other codes.
    

    The next paragraph is copied from the documentation ot TryGetValue-

    This method combines the functionality of the ContainsKey method and the Item property. If the key is not found, then the value parameter gets the appropriate default value for the type TValue; for example, 0 (zero) for integer types, false for Boolean types, and null for reference types. Use the TryGetValue method if your code frequently attempts to access keys that are not in the dictionary. Using this method is more efficient than catching the KeyNotFoundException thrown by the Item property. This method approaches an O(1) operation.

    BTW, ContainsKey and TryGetValue both has running time O(1). So, it does not matter much, you can use any.

提交回复
热议问题