Possible Duplicate:
Is there a C# case insensitive equals operator?
string string1 = "aBc"
string string2 = "AbC"
how can I check if string1 is equal to string2 and have it return true, regardless of case sensitivity.
Possible Duplicate:
Is there a C# case insensitive equals operator?
string string1 = "aBc"
string string2 = "AbC"
how can I check if string1 is equal to string2 and have it return true, regardless of case sensitivity.
Two approaches:
You can .ToLower()
and do string-equality, or you can use this:
string.Equals(string1, string2, StringComparison.CurrentCultureIgnoreCase)
Edit: To appease the downvoters, this operation is useful if your data is culturally significant (i.e., you're comparing Scandinavian words and your current locale is set correctly). If this data is culturally agnostic, and you don't care about locales (bad idea, particularly since .NET lives for Unicode), you can do this:
string.Equals(string1, string2, StringComparison.OrdinalIgnoreCase)
You should use the recommendations here MSDN: "Recommendations for String Use" :
I must admit they were an eyeopener for me. Especially the last one.
You can also use string.Compare, adding the third parameter, which is ignoreCase
:
if (string.Compare(string1, string2, true) == 0)
{
// string are equal
}
And you could use also the CompareInfo class:
if (CultureInfo.CurrentCulture.CompareInfo.Compare(string1, string2,
CompareOptions.IgnoreCase) == 0)
{
// string are equal
}
string.Equals(string1, string2, StringComparison.CurrentCultureIgnoreCase);
:D