Part 31. String Equals()


Part 31. String Equals()

equals() method is used to check two string value have same or not. will actually measure the equality of the values.if the value will match its return true otherwise false.


Example 1: class Program

    {
        static void Main(string[] args)
        {
            string s1 = "csharpTutorial";
            string s2 = "csharpTutorial";
            Console.WriteLine(s1.Equals(s2));
            Console.ReadLine();
        }
    }

Output :

Tr'ue


  • if both the string object having null values and its return true value.

Example 2:
class Program
    {
        static void Main(string[] args)
        {
            string s1 = "";
            string s2 = "";
            Console.WriteLine(s1.Equals(s1, s2));
            Console.ReadLine();
        }
    }

Output :

Tr'ue

 class Program

    {
         static void Main(string[] args)
        {
              string tutorial= "cSharpTutorial";
              string author= "chandan";
             Console.WriteLine("{0} Equals to {1}? : {2}", tutorialauthortutorial.Equals(author));
             Console.ReadLine();
        }

    }
Output
cSharpTutorial Equals to chandan? : False



Note : if the string compare in name is lower case and Alias Name is uppercase .in this situation it return false .

Example : 


Two string "Chandan" and "Chandan", Equals()it will return true but for "chandan" and "CHANDAN" it will return false.


class Program

    {
        static void Main(string[] args)
        {
            string  name = "chandan";
            string  AliasName = "CHANDAN";
            Console.WriteLine(name.Equals(AliasName));
            Console.ReadLine();
        }

    }
Output :
False


Note : Most of time i have seen common mistake of using equality operator “==” for comparing String instead always use equals() method.