Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is StringComparison.Ordinal the same as InvariantCulture for testing equality?

From their brief summary descriptions, it sounds like the string comparison rules StringComparison.Ordinal and StringComparison.InvariantCulture are meant to differ in how they do sorting of strings. Is that all? i.e., does that mean we can use either string comparison rule when doing an equality comparison?

string.Equals(a, b, StringComparison....)

And for extra credit: does it make a difference to the answer if we compare OrdinalIgnoreCase and InvariantCultureIgnoreCase? How?

Please provide supporting argument and/or references.

like image 285
Tim Lovell-Smith Avatar asked Jan 12 '11 22:01

Tim Lovell-Smith


People also ask

What is StringComparison InvariantCulture?

The StringComparison enumeration is used to specify whether a string comparison should use the current culture or the invariant culture, word or ordinal sort rules, and be case-sensitive or case-insensitive. Important.

What is the use of StringComparison OrdinalIgnoreCase?

OrdinalIgnoreCase. The StringComparison has the OrdinalIgnoreCase property and treats the characters in the strings to compare as if they were converted to uppercase (using the conventions of the invariant culture) and then it performs a simple byte comparison and it is independent of language.

What is StringComparison CurrentCultureIgnoreCase?

The StringComparer returned by the CurrentCultureIgnoreCase property can be used when strings are linguistically relevant but their case is not. For example, if strings are displayed to the user but case is unimportant, culture-sensitive, case-insensitive string comparison should be used to order the string data.


1 Answers

It does matter, for example - there is a thing called character expansion

    var s1 = "Strasse";
    var s2 = "Straße";

    s1.Equals(s2, StringComparison.Ordinal);          // false
    s1.Equals(s2, StringComparison.InvariantCulture); // true

With InvariantCulture the ß character gets expanded to ss.

like image 143
Ventsyslav Raikov Avatar answered Oct 03 '22 23:10

Ventsyslav Raikov