Skip to content

CA1853: Wrong code fix is suggested when arguments of ContainsKey and Remove differ  #6781

@mpidash

Description

@mpidash

Analyzer

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

Analyzer source

NuGet Package: Microsoft.CodeAnalysis.NetAnalyzers

Version: 8.0.0-preview.23320.2 (Latest)

Describe the bug

A code fix is suggested if ContainsKey is called with a different key than Remove. This results in incorrect code.

Steps To Reproduce

var dict = new Dictionary<string, string>();
var otherKey = "other";

if (dict.ContainsKey("key"))
    dict.Remove(otherKey);

which gets fixed to:

var dict = new Dictionary<string, string>();
var otherKey = "other";

dict.Remove(otherKey);

or as a test case:

[Fact]
public async Task ContainsAndAddCalledWithDifferentArguments_NoDiagnostic_CS()
{
    string source = CSUsings + CSNamespaceAndClassStart + @"
private readonly Dictionary<string, string> MyDictionary = new Dictionary<string, string>();
private const string KeyField = ""Field Key"";

public string KeyProperty { get; } = ""Property Key"";

public MyClass(string keyParameter)
{
    if (!MyDictionary.ContainsKey(""Key""))
        MyDictionary.Remove(""Other Key"");

    if (!MyDictionary.ContainsKey(""Key""))
        MyDictionary.Remove(keyParameter);

    if (!MyDictionary.ContainsKey(""Key""))
        MyDictionary.Remove(KeyField);

    if (!MyDictionary.ContainsKey(""Key""))
        MyDictionary.Remove(KeyProperty);
    
    string otherItemLocal = ""Other Key"";
    if (!MyDictionary.ContainsKey(""Key""))
        MyDictionary.Remove(otherItemLocal);
}" + CSNamespaceAndClassEnd;

    await VerifyCS.VerifyCodeFixAsync(source, source);
}

The above leads to 5 diagnostics.

Expected behavior

No code fix and no diagnostic is suggested.

Actual behavior

Code fix is suggested that leads to a different behavior.

Additional context

Found by @buyaa-n during #6767.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-Microsoft.CodeAnalysis.NetAnalyzersBugThe product is not behaving according to its current intended designhelp wantedThe issue is up-for-grabs, and can be claimed by commenting

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions