Equals Method in C#

Equals Method in C#

In this article, I am going to discuss the Equals method in C# with an example. Please read our previous article before proceeding to this article where we discussed why and how to override the ToString() method in C#. As part of this article, we are going to discuss the following pointers.

  1. Understanding the Equals method?
  2. Understanding the difference between “==” operator and the Equals() method in C#?
  3. Why do we need to override the Equals() method in C#?
  4. How we can override the Equals Method?
Understanding the difference between “==” operator and the Equals() method in C#?

In C#, as we already discussed every type directly or indirectly inherits from the Object class. So, the Equals() virtual method, which has a default implementation within the Object class is also available in every type via inheritance.

In the following example, the variables i and j are integers. So, both the == and Equals() method returns true, since i and j, both variables have the same value i.e. 10.

Why we need to Override the Equals Method in C#

In the following example, we compare 2 enums and both the == operator and Equals() method returns true since both direction1 and direction2 enums have the same underlying integer value of 1.

namespace UnderstandingObjectClassMethods
{
    public class Program
    {
        public static void Main()
        {
            Direction direction1 = Direction.East;
            Direction direction2 = Direction.East;            
            Console.WriteLine(direction1 == direction2);
            Console.WriteLine(direction1.Equals(direction2));
        }
    }
    public enum Direction
    {
        East = 1,
        West = 2,
        North = 3,
        South = 4
    }
}
Working with Reference Type:

If the type is a reference type, then by default the “==” operator checks for reference equality whereas the Equals() method checks for value equality. If this is not clear at the moment, don’t worry let us understand this with an example,

In the following example, C1 and C2 are 2 different object reference variables. But both are pointing to the same object. The most important point that you need to keep in mind is object reference variables are different from objects. Object reference variables are created on the stack and they point to the actual objects which are stored in the heap.

Since, C1 and C2 both refer to the same object, the reference equality, and the value equality is true. Value equality means that two objects contain the same values. In this example, the actual object is only one, so obviously, the values are also equal. If two objects have reference equality, then they also have value equality, but value equality does not guarantee reference equality.

namespace UnderstandingObjectClassMethods
{
    public class Program
    {
        public static void Main()
        {
            Customer C1 = new Customer();
            C1.FirstName = "Pranaya";
            C1.LastName = "Rout";
            
            Customer C2 = C1;
            
            Console.WriteLine(C1 == C2);
            Console.WriteLine(C1.Equals(C2));
        }
    }
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

In the following example, the == operator returns False. This makes sense because C1 and C2 are referring to different objects. However, the Equals() method returns false, in spite of the values across C1 and C2 being the same. Hence, it makes sense to override, the Equals() method to return true when the values across the objects are the same.

namespace UnderstandingObjectClassMethods
{
    public class Program
    {
        public static void Main()
        {
            Customer C1 = new Customer();
            C1.FirstName = "Pranaya";
            C1.LastName = "Rout";

            Customer C2 = new Customer();
            C2.FirstName = "Pranaya";
            C2.LastName = "Rout";

            Console.WriteLine(C1 == C2);
            Console.WriteLine(C1.Equals(C2));
        }
    }
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
Overriding the Equals Method in C#:

In the following example, we override the Equals() method. When overriding the Equals() method, make sure the passed in object is not null and can be cast to the type you are comparing. When overriding Equals(), you also need to override GetHashCode(), otherwise you get a compiler warning.

namespace UnderstandingObjectClassMethods
{
    public class Program
    {
        public static void Main()
        {
            Customer C1 = new Customer();
            C1.FirstName = "Pranaya";
            C1.LastName = "Rout";

            Customer C2 = new Customer();
            C2.FirstName = "Pranaya";
            C2.LastName = "Rout";

            Console.WriteLine(C1 == C2);
            Console.WriteLine(C1.Equals(C2));
        }
    }
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public override bool Equals(object obj)
        {
            // If the passed object is null
            if (obj == null)
            {
                return false;
            }
            if (!(obj is Customer))
            {
                return false;
            }
            return (this.FirstName == ((Customer)obj).FirstName)
                && (this.LastName == ((Customer)obj).LastName);
        }

        public override int GetHashCode()
        {
            return FirstName.GetHashCode() ^ LastName.GetHashCode();
        }
    }
}

In the next article, I am going to discuss the difference between convert.tostring and ToString() method in c#.  In this article, I try to explain why we should override the Equals method in C# with an example. I hope you understood why and how to override the Equals() method in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *