Skip to content

[Analyzer] Recommend string.ToLower{Invariant}().Contains/IndexOf/StartsWith("lowercasestring") be replaced by case-insensitive comparison #78606

@stephentoub

Description

@stephentoub

There's a significant amount of code that's apparently trying to perform case-insensitive comparisons by first lower-casing and then comparing against a lowercased string, e.g.
https://grep.app/search?q=.ToLower%28%29.Contains&filter[lang][0]=C%23
https://grep.app/search?q=.ToLower%28%29.IndexOf&filter[lang][0]=C%23
https://grep.app/search?q=.ToLower%28%29.StartsWith&filter[lang][0]=C%23
Less but still many for ToUpper with upper-case, e.g.
https://grep.app/search?q=.ToUpper%28%29.Contains&filter[lang][0]=C%23
https://grep.app/search?q=.ToUpper%28%29.IndexOf&filter[lang][0]=C%23
https://grep.app/search?q=.ToUpper%28%29.StartsWith&filter[lang][0]=C%23
and with the Invariant variations, e.g.
https://grep.app/search?q=.ToLowerInvariant%28%29.Contains&filter[lang][0]=C%23

We should write an analyzer that flags these patterns and recommends comparisons using a StringComparison instead.

Such analyzers will help avoid the allocations caused by ToLower/ToUpper calls.

Performance rules Category
Severity = suggestion

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Globalizationcode-analyzerMarks an issue that suggests a Roslyn analyzercode-fixerMarks an issue that suggests a Roslyn code fixerin-prThere is an active PR which will close this issue when it is mergedpartner-impactThis issue impacts a partner who needs to be kept updated

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions