JackBarn
JackBarn

Reputation: 645

Is String culture info important for comparison if the user will never modify those strings

When comparing hard-coded Strings that the User will see but not modify/change, is the culture info important.

I would assume not, but I just want to be safe.

Example:

static void Main()
{
    string hardString = "IAMHardCodei";
    string hardString2 = "IamHardCodei";
    //Compare hardString and hardString2, ignoring case, 
    //and then do stuff based on that result
}

Upvotes: 1

Views: 719

Answers (3)

user1726343
user1726343

Reputation:

Culture rules are relevant even for hardcoded strings if you're relying on the default CurrentCulture when doing comparisons. Here's a textbook example out of the MSDN documentation:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US")
Debug.Assert("file" == "FILE".ToLower()); // Passes

Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR");
Debug.Assert("file" == "FILE".ToLower()); // Fails

With case insensitive comparison, your users computers in Turkey don't think file and FILE are identical, whereas in the US they are identical.

Upvotes: 1

CodingGorilla
CodingGorilla

Reputation: 19842

The general recommendation for string comparisons when they are "programmatic only strings" (i.e. as you specified they are not usable or editable by the user directly is the: StringComparison.Ordinal[IgnoreCase].

See this SO post (of which this is probably a duplicate): Which is generally best to use -- StringComparison.OrdinalIgnoreCase or StringComparison.InvariantCultureIgnoreCase?

Upvotes: 0

VMAtm
VMAtm

Reputation: 28345

You can use InvariantCultureIgnoreCase for the comparing

hardString.Equals(hardString2, StringComparison.InvariantCultureIgnoreCase);

Upvotes: 1

Related Questions