C#

difference between equality operator and equals method


C# has provided two ways of doing comparison “==” and an overloaded method “equals()”.

So in this blog we will discuss about differences between them and when to use what.
Whenever you are comparing variables they are either value types or reference types. When values types are compared they are compared on the basis of “Content” when reference types are compared they are compared on the basis of “Reference”(memory location) and not “Content”.


Value type comparison

When you compare value types / primitive data types ( int , double etc) either by using “==” or “Equals” it’s always based on content. In the below code you can see both comparison methods will show as “true”.

using System;
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 100;
            int b = 100;
            //return true
            Console.WriteLine(string.Format("== operator result = {0}",a==b));
            //return true
            Console.WriteLine(string.Format("Equal() method result = {0}",a.Equals(b)));

            Console.ReadLine();
        }
    }
}


Reference types comparison:

Now when you compare objects they are compared on the basis of reference (internal memory pointer). Below obj and obj1 comparison either through “==” or “Equals” will be false. So in the below code even though both the object have property name as “Welcome” still it shows unequal. Because the comparison is based on internal memory reference which is different for “obj” and “obj1”.

using System;
namespace Test
{
    class Student
    {
        public string Name { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Student obj = new Student();
            obj.Name = "Ram";

            Student obj1 = new Student();
            obj1.Name = "Ram";

            //return false
            Console.WriteLine(string.Format("== operator result = {0}",obj==obj1));
            //return false
            Console.WriteLine(string.Format("Equal() method result = {0}",obj.Equals(obj1)));

            Console.ReadLine();
        }
    }
}

But the below code will display true as the pointer points to same object.
Student obj = new Student();
            obj.Name = "Ram";

            Student obj1 = obj;

            //return true
            Console.WriteLine(string.Format("== operator result = {0}",obj==obj1));
            //return true
            Console.WriteLine(string.Format("Equal() method result = {0}",obj.Equals(obj1)));

Compile time VS RunTime
The next point which makes them different is when do type checks happen. “==” does type checking during compile time while “Equals” is more during runtime. You can see in the below code how “==” is showing a warning message with green sign saying that you are comparing different types and you can have issues. “Equals” does not show any such warnings.


The NULL Situation:-

“==” works with nulls but “Equals” crashes when you compare NULL values , see the below print screen.

NOTE:à  == is a binary operator, while equals() is a method.


Another Examples:

 we assigned a string variable to another variable. A string is a reference type and in the following example, a string variable is assigned to another string variable so they are referring to the same identity in the heap and both have the same content so you get True output for both the == Operator and the Equals() method.
using System;
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Hello";
            string str1 = str;
            Console.WriteLine(string.Format("== operator result = {0}",str==str1));
            Console.WriteLine(string.Format("Equal() method result = {0}",str1.Equals(str)));
            Console.ReadLine();
        }
    }
}

Now run the program and get the results as in Figure


Let’s see another example where the contents will be the same in both object variables but both have different references. So the == Operator returns False because it compares the reference identity while the Equals() method returns True because it compares the contents of the objects.

using System;
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            object str = "Hello";
            char[] charArr = { 'H','e','l','l','o' };
            object str1 = new string(charArr);

            Console.WriteLine(string.Format("== operator result = {0}",str==str1));
            Console.WriteLine(string.Format("Equal() method result = {0}",str1.Equals(str)));
            Console.ReadLine();
        }
    }
}

Now run the program and get the result as in Figure 1.2

Output of program


So when to use “==” and when to use “Equals”:-

Use  Equality Operator ( ==) if you are comparing reference with content and use Equals() method if you are comparing content not reference.


No comments:

Post a Comment