Pattern: Missing use of IDictionary.TryGetValue()
Issue: -
When an element of an IDictionary
is accessed, the indexer implementation checks for a null value by calling the IDictionary.ContainsKey
method. If you also call IDictionary.ContainsKey
in an if
clause to guard a value lookup, two lookups are performed when only one is needed.
Example of incorrect code:
public string? GetValue(string key)
{
if (_dictionary.ContainsKey(key)) // 1st check
{
return _dictionary[key]; // 2nd check
}
return null;
}
Example of correct code:
public string? GetValue(string key)
{
if (_dictionary.TryGetValue(key, out string? value))
{
return value;
}
return null;
}