-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
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
For the case when not passing StringComparison parameter
Severity = none (off by default)