-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Don't guard Dictionary<K, V>.Remove(key) by ContainsKey(key) #33797
Comments
Estimates:
|
Suggested severity: Info Example// Before
public void RemoveValue(Dictionary<string, int> data, string key)
{
if (data.ContainsKey(key))
data.Remove(key);
// or
if (data.ContainsKey(key))
data.Remove(key, out var value);
}
// After
public void RemoveValue(Dictionary<string, int> data, string key)
{
data.Remove(key);
// or
data.Remove(key, out var value1);
} Avoid triggering the analyzer if there's additional code inside the if statement: public void DontTrigger(Dictionary<string, int> data, string key, Dictionary<string, int> otherData)
{
if (data.ContainsKey(key))
{
otherData[key] = data[key]; // Unrelated code
data.Remove(key);
}
} |
We could further improve the fixer to handle this as well: // Before
if (data.ContainsKey(key))
{
data.Remove(key);
SomeUnrelatedCode();
}
// After
if (data.Remove(key))
{
SomeUnrelatedCode();
} But it's not necessary -- we can start simple and take it from there. |
I have the analyzer mostly ready to go for both C# and VB. No fixer yet, though. Do you want a PR, or should I first write a fixer? |
Thanks for your help, @chucker! I'm assigning the issue to you. Feel free to submit a PR whenever you get a chance, and we can take a look. |
(The PR linked above does now include the fixer, too.) |
is there an issue like this for
|
@paulomorgado if you can't find any issue, please create an API proposal. |
An API proposal???? |
@paulomorgado yes — make a new issue over here See also these guidelines. |
The pair can be combined into just the
Remove
call.Category: Performance
The text was updated successfully, but these errors were encountered: