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 = "java2s.com";
        string s2 = "java2s.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 = "java2s.com";
        string s2 = "java2s.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 = "java2s.com";
        string s2 = "java2s.coM";

        if (s1.Equals(s2, StringComparison.OrdinalIgnoreCase))
        {
            Console.WriteLine("equal");
        }
    }
}

The output:


equal
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.