C
C#10mo ago
JochCool

Getting warning CA1309 when explicitly setting string comparison

I have code analysis mode set to Recommended in my project because it often helps me find subtle bugs. It triggered a warning (CA1309: Use ordinal string comparison) on this line of code, but I don't know why:
C#
if (string.Equals(otherName, name, StringComparison.InvariantCultureIgnoreCase))
C#
if (string.Equals(otherName, name, StringComparison.InvariantCultureIgnoreCase))
If I look at the docs page for this rule, it seems to me like this was intended for situations like name.CompareTo(otherName) where you might accidentally use the thread's current culture, which is bad. But in this case I am explicitly saying that I want a linguistic sort, not an ordinal sort, because names that are basically the same should be treated as the same. So is this warning wrong? Or am I misunderstanding how the method works? Or are there downsides to using the invariant culture?
CA1309: Use ordinal StringComparison (code analysis) - .NET
Learn about code analysis rule CA1309: Use ordinal StringComparison
5 Replies
mtreit
mtreit10mo ago
Ordinal is much faster.
mtreit
mtreit10mo ago
Here is a benchmark for doing case insensitive string comparison:
No description
mtreit
mtreit10mo ago
https://github.com/Treit/MiscBenchmarks/tree/main/CaseInsensitiveStringComparison Basically if ordinal meets your needs you should use it since it is more efficient.
reflectronic
reflectronic10mo ago
is that really a reccomended rule? that seems strange it warns whenever you use anything other than Ordinal/OrdinalIgnoreCase
dreadfullydistinct
It does say to suppress it if you want culture sensitivity. I guess some of the more pedantic rules can’t always be right
It is safe to suppress a warning from this rule when the library or application is intended for a limited local audience, or when the semantics of the current culture should be used.
Want results from more Discord servers?
Add your server