Tuesday 3 May 2011

Dot.Net: Compare strings ignore case

Question:
How to compare two strings and ignore the case?
How to compare string upper and lower mixed?


Answer:
Instead of using the "==" you should use the Equals method. It has an overload with a parameter that determines the way strings are compared.
In most cases InvariantCultureIgnoreCase is what you want.

Here is an example
 string s1 = "toto";
 string s2 = "TotO";
 s1.Equals(s2, StringComparison.InvariantCultureIgnoreCase);
 // this is true


No comments: