ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

Code inspection: Dictionary lookup can be simplified with 'TryGetValue'

Last modified: 05 June 2024

This inspection suggests that you can simplify dictionary lookup by using the TryGetValue method instead of the ContainsKey followed by the index accessor.

ContainsKey and the index accessor both look up the key in the dictionary, which means that you are doing the same operation twice — first to check if the key exists, and then to actually retrieve the value.

TryGetValue combines these operations, performing the dictionary lookup only once. It attempts to get the value associated with the specified key. If the key exists, it returns true and assigns the value associated with the key to the variable. If the key does not exist, it returns false, and the output variable is given the default value for the type of the values in the dictionary.