C#idiomatic C#
ca1853fundamentals/code-analysis/quality-rules

Code analysis

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

Learn about code analyzer rule CA1853 - Unnecessary call to 'Dictionary.ContainsKey(key)'.

CA1853 Performance enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingIntroduced version .NET 7Applicable languages C# and Visual Basic

Cause

A call to System.Collections.Generic.Dictionary.Remove() is guarded with a call to System.Collections.Generic.Dictionary.ContainsKey().

Rule description

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

Example

The following code snippet shows a violation of CA1853:

csharp
Dictionary<string, int> d = new();
if (d.ContainsKey("name"))
    d.Remove("name");
vb
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:

csharp
Dictionary<string, int> d = new();
d.Remove("name");
vb
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.

csharp
#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.

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

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