ReSharper 2024.1 Help

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

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.

void WriteValue(IDictionary<int, int> dictionary, int key) { if (dictionary.ContainsKey(key)) { Console.WriteLine(dictionary[key]); } }
void WriteValue(IDictionary<int, int> dictionary, int key) { if (dictionary.TryGetValue(key, out var value)) { Console.WriteLine(value); } }
Last modified: 05 June 2024