A call to Dictionary<TKey,TValue>.Remove(TKey) is guarded with a call to Dictionary<TKey,TValue>.ContainsKey(TKey).
Rule descriptionThere'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.
Remove the guarding code that calls Dictionary<TKey,TValue>.ContainsKey(TKey).
ExampleThe 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 warningIf 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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4