Language
Edit

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 10 As suggestion
Applicable languages C# and Visual Basic

Cause

A call to Dictionary.Remove(TKey) is guarded with a call to Dictionary.ContainsKey(TKey).

Rule description

There's no need to guard Dictionary.Remove(key) with Dictionary.ContainsKey(key). Dictionary.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.ContainsKey(TKey).

Example

The following code snippet shows a violation of CA1853:

Dictionary 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 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.