JetBrains Rider 2024.1 Help

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

Category

Common Practices and Code Improvements

ID

CanSimplifyDictionaryLookupWithTryAdd

EditorConfig

resharper_can_simplify_dictionary_lookup_with_try_add_highlighting

Default severity

Suggestion

Language

C#

Requires SWA

No

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: 17 April 2024