CA1853: Unnecessary call to 'Dictionary.ContainsKey(key)'

Property Value
Rule ID CA1853
Title Unnecessary call to 'Dictionary.ContainsKey(key)'
Category Performance
Fix is breaking or non-breaking Non-breaking
Introduced version .NET 7
Enabled by default in .NET 8 As suggestion

Cause

A call to Dictionary<TKey,TValue>.Remove(TKey) is guarded with a call to Dictionary<TKey,TValue>.ContainsKey(TKey).

Rule description

There's no need to guard Dictionary.Remove(key) with Dictionary.ContainsKey(key). Dictionary<TKey,TValue>.Remove(TKey) already checks whether the key exists and doesn't throw if it doesn't exist.

How to fix violations

Remove the guarding code that calls Dictionary<TKey,TValue>.ContainsKey(TKey).

Example

The following code snippet shows a violation of CA1853:

Dictionary<string, int> d = new();
if (d.ContainsKey("name"))
    d.Remove("name");
Class C
    Shared Sub S()
        Dim d As New Dictionary(Of String, Integer)
        If d.ContainsKey("name") Then
            d.Remove("name")
        End If
    End Sub
End Class

The following code snippet fixes the violation:

Dictionary<string, int> d = new();
d.Remove("name");
Class C
    Shared Sub S()
        Dim d As New Dictionary(Of String, Integer)
        d.Remove("name")
    End Sub
End Class

When to suppress warnings

It's safe to suppress a warning if performance isn't a concern.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA1853
// The code that's violating the rule is on this line.
#pragma warning restore CA1853

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA1853.severity = none

For more information, see How to suppress code analysis warnings.