Royi Namir
Royi Namir

Reputation: 148524

StringComparison vs CompareOptions in C#?

After reading this I'm still confused :

 string s1 = "hello";
 string s2 = "héllo";

The difference thing here is the accent/culture.

The result of the following code is False.

Console.WriteLine(s1.Equals(s2, StringComparison.InvariantCulture));

But Im using invariant culture , so it should treat é as e.( default is English ,no?)

it seems that I have to go all the way to use

String.Compare(String, String, CultureInfo, CompareOptions) 

like

  string.Compare(s1, s2, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) //true

But , my current culture is he-IL so I have no CLUE why it is working.

so :

Upvotes: 1

Views: 1932

Answers (1)

user7116
user7116

Reputation: 64078

Your confusion with InvariantCulture is pretty common. The best use for this is when you are persisting data to and from a file and do not care about a given culture's oddities (such as , as a decimal separator or spelling flavor with a 'u').

It has limited use in comparisons, especially when you need culture specific behavior. It may not seem obvious on face value, but comparing e with an acute accent to be the same as e without one...well that is situation dependent.

Aha! Situation dependent you say.

Looks like a job for a culture specific overload. Anytime you know which culture you are using, you should pass that culture along.

In this case, you would like .Net to ignore diacritical marks (p. ex. accent aigu), hence you should also use an overload which accepts CompareOptions (specifically as you noted CompareOptions.IgnoreNonSpace).

Upvotes: 4

Related Questions