KEMBAR78
[Analyzer] Recommend string.StartsWith(c) instead of string.StartsWith("c") · Issue #78392 · dotnet/runtime · GitHub
Skip to content

[Analyzer] Recommend string.StartsWith(c) instead of string.StartsWith("c") #78392

@stephentoub

Description

@stephentoub

We should consider adding an analyzer that recommends using the char-based StartsWith(char) instead of StartsWith(string, ...) when the string is a constant single character. The former is more optimized.

However, this can have observable behavioral differences. string.StartsWith(char) is ordinal, whereas string.StartsWith(string) uses the current culture. This, for example, prints True and then False, highlighting that there can be semantic differences due to culture:

using System.Globalization;

CultureInfo.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("\u0061\u030a".StartsWith("\u00e5"));
Console.WriteLine("\u0061\u030a".StartsWith('\u00e5'));

It would be safe to replace string.StartsWith("c", StringComparison.Ordinal) with string.StartsWith('c') for arbitrary characters. We could do that with one diagnostic ID, and have a separate diagnostic ID (potentially off by default) for the potentially problematic case.

Same for EndsWith, IndexOf, and LastIndexOf.

Proposal to have 2 analyzers with Performance rules Category

For the case when passing StringComparison.Ordinal

Severity = suggestion

For the case when not passing StringComparison parameter

Severity = none (off by default)

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 fixerhelp wanted[up-for-grabs] Good issue for external contributorspartner-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