All rules
CA1854Performance Enabled by default: As suggestion

Prefer the IDictionary.TryGetValue(TKey, out TValue) method

Prefer the IDictionary.TryGetValue(TKey, out TValue) method

Microsoft docs

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.

Cause

An IDictionary element access that's guarded by an IDictionary.ContainsKey check.

How to fix violations

Replace the IDictionary.ContainsKey invocation and element access with a call to the IDictionary.TryGetValue method.

Violation:

Fix:

Example

public string? GetValue(string key)
{
    if (_dictionary.ContainsKey(key))
    {
        return _dictionary[key];
    }

    return null;
}

When to suppress

It's safe to suppress this warning if you're using a custom implementation of IDictionary that avoids a value lookup when performing the IDictionary.ContainsKey check.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0