Dani Avni
Dani Avni

Reputation: 435

Strange behavior of String.Compare with OrdinalIgnoreCase

MSDN says on StringComparison.OrdinalIgnoreCase the following:

TheStringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames.

(https://msdn.microsoft.com/en-us/library/e6883c06(v=vs.110).aspx and https://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396)

However, when I try to compare

String.Compare("‎a","A", StringComparison.OrdinalIgnoreCase)

The returned value is 1 and not 0.

Even stranger is this:

String.Compare("‎1","1", StringComparison.OrdinalIgnoreCase)

which also returns 1 although strings are equal.

What am I missing?

Upvotes: 2

Views: 101

Answers (2)

Dani Avni
Dani Avni

Reputation: 435

Found the reason after an hour of digging: Turns out one of the strings contains an invisible character %e2%80%8e (LEFT-TO-RIGHT MARK) which is only visible when taking the string and converting it to an array.

Upvotes: 2

Jehof
Jehof

Reputation: 35544

I´m not sure why you get this result. When I run this code via LinqPad I get 0.

If casing is not relevant you can try the other overload String.Compare(string, string, bool)

String.Compare("‎a","A", true);
String.Compare("‎1","1", true);

Upvotes: 1

Related Questions