Skip to content
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

New rule: Use Dictionary.TryGetValue instead of Dictionary.ContainsKey followed by a lookup #184

Closed
ghost opened this issue Aug 20, 2020 · 1 comment

Comments

@ghost
Copy link

ghost commented Aug 20, 2020

I never wrote an analyzer, so I am not certain of what is possible api-wise, but I think this perf rule could be useful:

When the dictionary value is a reference type and a ContainsKey is followed by a lookup:

            // Two lookups...
            if (dic.ContainsKey("key"))
            {
                Poco poco = dic["key"];
            }

It should suggest the use of TryGetValue:

            // Single lookup
            if (dic.TryGetValue("key",out Poco poco))
            {

            }
@meziantou
Copy link
Owner

Everything's possible :)

The rule has already been suggested in the .NET repository dotnet/runtime#33798 and will be probably available in Microsoft.CodeAnalysis.FxCopAnalyzers in a few weeks/months. I don't want to implement a rule that is available in FxCop or will be available in this analyzer because it would just be duplicated work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant