-
Notifications
You must be signed in to change notification settings - Fork 480
Closed
Labels
Area-Microsoft.CodeAnalysis.NetAnalyzersBugThe product is not behaving according to its current intended designThe product is not behaving according to its current intended designhelp wantedThe issue is up-for-grabs, and can be claimed by commentingThe issue is up-for-grabs, and can be claimed by commenting
Description
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
Metadata
Metadata
Assignees
Labels
Area-Microsoft.CodeAnalysis.NetAnalyzersBugThe product is not behaving according to its current intended designThe product is not behaving according to its current intended designhelp wantedThe issue is up-for-grabs, and can be claimed by commentingThe issue is up-for-grabs, and can be claimed by commenting