ReSharper 2024.3 Help

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

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.

void AssignValue(int key, int newValue, Dictionary<int, int> dict) { if (!dict.ContainsKey(key)) { dict[key] = newValue; } }
void AssignValue(int key, int newValue, Dictionary<int, int> dict) { dict.TryAdd(key, newValue); }
Last modified: 04 June 2024