Mega Code Archive

 
Categories / C# Book / 02 Essential Types
 

0248 String comparison for equality

We can use == to check the equality between two string values using System; class Sample { public static void Main() { string s1 = "rntsoft.com"; string s2 = "rntsoft.coM"; if (s1.ToUpper() == s2.ToUpper()) { Console.WriteLine("equal"); } } } The output: equal Equals method from string type provides the same functionality and adds more features. using System; class Sample { public static void Main() { string s1 = "rntsoft.com"; string s2 = "rntsoft.coM"; if (s1.ToUpper().Equals(s2.ToUpper())) { Console.WriteLine("equal"); } } } The output: equal Further more we can compare two string ignoring the case by specifying case-insensitive option. using System; class Sample { public static void Main() { string s1 = "rntsoft.com"; string s2 = "rntsoft.coM"; if (s1.Equals(s2, StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("equal"); } } } The output: equal