Tuesday, 14 February 2017

IEquatable

The IEquatable defines a generalized function that a class implements to determine if two instances are "equal". If we create a basic implementation of a "Person" class

class Person {
    public string FirstName { get; set; }
    public string LastName { get; set; }

}

And in our main we create two instances of the person class, both of which have the same first and last name

using System;

namespace pc.IEquatableExample
{
    class Person {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var p1 = new Person { FirstName = "Pawel", LastName = "Ciucias" };
            var p2 = new Person { FirstName = "Pawel", LastName = "Ciucias" };

            Console.WriteLine($"p1 is the same as p2:" + p1.Equals(p2));
        }
    }
}

but if we run the code above, p1.Equals(p2) returns false because by default the equals function checks if the the two objects reference the same object. if we had something like the following

static void Main(string[] args)
{
    var p1 = new Person { FirstName = "Pawel", LastName = "Ciucias" };
    var p2 = p1;

    Console.WriteLine($"p1 is the same as p2:" + p1.Equals(p1));

}

our result would be true, however if we implement the IEquatable<Person> we could compare two different instances of our person class and determine if by their properties the are equal instead of their reference.

using System;

namespace pc.IEquatableExample
{
    class Person : IEquatable<Person>
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool Equals(Person other)
        {
            return FirstName == other.FirstName &&
                LastName == other.LastName;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var p1 = new Person { FirstName = "Pawel", LastName = "Ciucias" };
            var p2 = new Person { FirstName = "Pawel", LastName = "Ciucias" };

            Console.WriteLine($"p1 is the same as p2:" + p1.Equals(p1));
        }
    }

}

in the above because we implemented IEquatable in our Person class p1.Equals(p2) returns true.