Description
Methods which take StringComparison
are not sufficiently clear about how hard they are to use correctly
I claim that it is easy to read e.g. https://learn.microsoft.com/en-us/dotnet/api/system.string.endswith?view=net-8.0 and come away thinking that "I'll be fine, I'll just stick with the invariant culture because I don't care about anything above code point 127". This is amply discussed in Best Practices for Using Strings, and the docs do vaguely suggest that perhaps you might want to read it; but I believe what is actually required in the Notes to Callers is "you must read Best Practices for Using Strings, in full, before using any method that can take a StringComparison".
In particular, for example, the following documentation (which is where one would naturally look to find the "non-printing characters are omitted in most configurations" footgun) is entirely unhelpful except insofar as it suggests that you might want to read the document whose purpose is to instil the correct sense of unease:
As explained in Best Practices for Using Strings, we recommend that you avoid calling string comparison methods that substitute default values and instead call methods that require parameters to be explicitly specified. To determine whether a string ends with a particular substring by using the string comparison rules of the current culture, call the EndsWith(String, StringComparison) method overload with a value of CurrentCulture for its comparisonType parameter.
I read this paragraph entirely as "string comparison is culture-specific, so be careful about which culture you're in", and not as the much more important "… and also bear in mind that you probably do not know what any given culture's string comparison rules are, even if you think you do".
I believe every method which has an overload which takes a StringComparison
should contain a Note to Callers that warns the user that they must read the Best Practices. If I were writing the docs, they would say the following:
You must read Best Practices in full before using this function, even if you think you currently know what a culture-sensitive comparison is. Read it all; do not just read the section about the
StringComparison
you currently intend using. (You may skip this step if you can already articulate why the invariant culture is almost never the correct culture to use for string comparison and related operations.)
Target framework
True of .NET 5 through at least .NET 8.
- .NET Core
- [ ? ] .NET Framework
- .NET Standard