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 'TryAdd'

Last modified: 04 June 2024

This inspection suggests that you can simplify the dictionary lookup by using the TryAdd method instead of the ContainsKey and bracket notation.

TryAdd is a method that attempts to add the specified key and value to the dictionary. If the key already exists in the dictionary, it returns false and does not add the key-value pair. If the key does not exist, it adds the key-value pair to the dictionary and returns true.

Using TryAdd instead of ContainsKey and bracket notation can simplify your code and make it more readable. It also has the added benefit of being more performant, as it reduces the number of dictionary lookups needed to add a new key-value pair.