I just recently noticed Dictionary.TryGetValue(TKey key, out TValue value) and was curious as to which is the better approach to retrieving a value from the Dictionary.
I’ve traditionally done:
if (myDict.Contains(someKey)) someVal = myDict[someKey]; ...
unless I know it has to be in there.
Is it better to just do:
if (myDict.TryGetValue(somekey, out someVal) ...
Which is the better practice? Is one faster than the other? I would imagine that the Try version would be slower as its ‘swallowing’ a try/catch inside itself and using that as logic, no?
TryGetValue is slightly faster, because FindEntry will only be called once.
FYI: It’s not actually catching an error.
It’s calling:
ContainsKey is this: