IComparable, IComparer And IEquatable Interfaces In C#

IComparable Interface

The CompareTo method of the interface takes a reference type as a parameter and returns an integer based on whether the current instance comes before, after, or is in the same position in the sort order as the other object (MSDN).

The CompareTo(Object) method’s implementation must return an Int32 with one of the three values shown in the table below.

Value Meaning
Less than zero In the sort order, the current instance comes before the object specified by the CompareTo method.
Zero This current instance is sorted in the same order as the object specified by the CompareTo method.
Greater than zero In the sort order, this current instance comes after the object specified by the CompareTo method.

 Example

public class Car: IComparable
{
    public string Name
    {
        get;
        set;
    }
    public int MaxSpeed
    {
        get;
        set;
    }
    public int CompareTo(object obj)
    {
        if (!(obj is Car))
        {
            throw new ArgumentException("Compared Object is not of car");
        }
        Car car = obj as Car;
        return Name.CompareTo(car.Name);
    }
}

Main method

private static void Main(string[] args)
{
    Car[] cars = new Car[]
    {
        new Car()
        {
            Name = "Zinco"
        }, new Car()
        {
            Name = "VW"
        }, new Car()
        {
            Name = "BMW"
        }
    };
    Array.Sort(cars);
    Array.ForEach(cars, x => Console.WriteLine(x.Name));
}

IComparer interface

The CompareTo method of the IComparable interface can only sort on one field at a time, sorting on multiple properties is not possible. The Compare method of the IComparer interface compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.

A class that implements the IComparer interface must implement the Compare method, which compares two objects.

For instance, you could write a CarComparer class that implements IComparer and has a Compare method that compares Car objects based on their names. The Array could then be passed a CarComparer object. Sort method, which can be used to sort an array of Car objects.

public class CarComparer: IComparer < Car >
{
    public enum SortBy
    {
        Name,
        MaxSpeed
    }
    private SortBy compareField = SortBy.Name;
    public int Compare(Car x, Car y)
    {
        switch (compareField)
        {
            case SortBy.Name:
                return x.Name.CompareTo(y.Name);
                break;
            case SortBy.MaxSpeed:
                return x.MaxSpeed.CompareTo(y.MaxSpeed);
                break;
            default:
                break;
        }
        return x.Name.CompareTo(y.Name);
    }
}

Mainmethod

private static void Main(string[] args)
{
    Car[] cars = new Car[]
    {
        new Car()
        {
            Name = "Zinco"
        }, new Car()
        {
            Name = "VW"
        }, new Car()
        {
            Name = "BMW"
        }
    };
    var carComparer = new CarComparer();
    carComparer.compareField = CarComparer.SortBy.MaxSpeed;
    Array.Sort(cars, carComparer);
}

IEquatable Interface

If a class implements the IComparable interface, it includes a CompareTo method for determining how two objects should be ordered. Sometimes it is not necessary to know how two objects should be ordered, but rather whether the objects are equal. The IEquatable interface enables this by requiring a class to implement an Equals method.

class Employee: IEquatable < Person >
{
    public string FirstName
    {
        get;
        set;
    }
    public string LastName
    {
        get;
        set;
    }
    public bool Equals(Employee other)
    {
        return ((FirstName == other.FirstName) && (LastName == other.LastName));
    }
}

Client Method

// The List of Persons.
private List < Employee > Employees = new List < Employee > ();
// Add a Person to the List.
// Make the new Person.
Employee emp = new Employee()
{
    FirstName = “James”
    LastName = “Moore”
};
if (Employees.Contains(emp))
{
    MessageBox.Show("The list already contains this employee.");
}

Submit a Comment

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

Subscribe

Select Categories