-
Notifications
You must be signed in to change notification settings - Fork 4.9k
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
Prefer Dictionary<K, V>.TryGetValue() over guarded indexer access #33798
Labels
api-approved
API was approved in API review, it can be implemented
area-System.Collections
code-analyzer
Marks an issue that suggests a Roslyn analyzer
code-fixer
Marks an issue that suggests a Roslyn code fixer
Milestone
Comments
Estimates:
|
Suggested severity: info // Before
public int TryGet(Dictionary<string, int> data, string key)
{
if (data.ContainsKey(key))
{
return data[key];
}
return 0;
}
// After
public int TryGet(Dictionary<string, int> data, string key)
{
if (data.TryGetValue(key, out int value))
{
return value;
}
return 0;
} It may be possible to preserve unrelated code inside the // Before
public int TryGet(Dictionary<string, int> data, string key)
{
if (data.ContainsKey(key))
{
Foo(data[key]); // Unrelated code
return data[key];
}
return 0;
}
// After
public int TryGet(Dictionary<string, int> data, string key)
{
if (data.TryGetValue(key, out int value))
{
Foo(value); // Unrelated code
return value;
}
return 0;
} Avoid triggering if the data is modified before returning: public int DontTrigger(Dictionary<string, int> data, string key)
{
if (data.ContainsKey(key))
{
data[key] = DoSoemthing(data[key]); // Unrelated code
return data[key];
}
return 0;
} |
Contributor
Author
|
I'd like to do this one. @carlossanlop |
It's yours, @CollinAlpert . Thanks for offering your help! |
Closed
18 tasks
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Labels
api-approved
API was approved in API review, it can be implemented
area-System.Collections
code-analyzer
Marks an issue that suggests a Roslyn analyzer
code-fixer
Marks an issue that suggests a Roslyn code fixer
Dictionary<K, V>.ContainsKey(key)
followed byDictionary<K, V>.this[key]
can be combined into a singleTryGetValue
call.Category: Performance
The text was updated successfully, but these errors were encountered: