Skip to content

Files

Latest commit

 

History

History
39 lines (28 loc) · 887 Bytes

File metadata and controls

39 lines (28 loc) · 887 Bytes

Pattern: Missing use of IDictionary.TryGetValue()

Issue: -

Description

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;
}

Further Reading