Using the IComparable interface example C#.Net


Earlier on this blog I went over what interfaces were about and gave a small demo. One of the most known interfaces used in C# is IComparable. This interface is used for comparison of two different objects so that, for example, later on if we a collection of objects we can use the interface to sort those objects.  Implementing IComparable means that the class you are implementing it with needs to implement the CompareTo() method (returns an int value).

For example, below we have a class called Car that implements the IComparable interface by implicitly implementing the CompareTo() method

    class Car : IComparable<Car>
    {
        private string make;
        private int year;
        public Car(string make, int year)
        { this.make = make; this.year = year; }
        public int CompareTo(Car next)//compareto compares by the make of the car
        {
            if (String.Compare(this.make, next.make) == -1)
            {
                return -1;
            }
            if (String.Compare(this.make, next.make) == 1)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        public int Year() { return this.year; }
        public string Make() { return this.make; }
    }

In addition to IComparable, we also have the IComparer interface that can be implemented to a certain class that can be used to compare two objects and return an int type.

class CompareByYear : IComparer<Car>//CompareByYear implements IComparer<Car> and compares two Car objects by year
    {
        //Implicit implementation compares by year as opposed to make
        public int Compare(Car x, Car y)
        {
            return x.Year().CompareTo(y.Year());
        }
    }

In the Program class, we will use what we implemented to make a List and sort that list according to the CompareTo() method.

            List<Car> l = new List<Car>();
            l.Add(new Car("Porsche", 2014));
            l.Add(new Car("Renault", 2008));
            l.Add(new Car("Mercedes", 2010));
            l.Add(new Car("Ferrari", 2012));
            l.Add(new Car("Aston Martin", 2007));

            l.Sort();//this sorts by Name using the CompareTo() implemented in Car
            l.Sort(new CompareByYear());//this sorts Car objects using Compare() implemented in CompareByYear class

More on Implicit vs Explicit implementation of interfaces

When we implement any interface, we can either do it explicitly or implicitly. To make this clearer, suppose we have two interfaces with the same method name & type. And we have a class that will inherit both of these interfaces. If we were to implement the Print() method implicitly, that would mean whatever is implemented in the class that’s inheriting from is representative of both interfaces. However, if we implement explicitly, we can have different implementations for each method thats inherited from each interface. In the example below, we have a class called Write that implements two interfaces called Test & Test2 both with methods called Print(), respectively. The class implements the Print method both implicitly and explicitly. Please also pay attention to when declaring new instances of Interfaces to use the explicitly implemented methods.

    interface Test
    {
        void Print();
    }
    interface Test2
    {
        void Print();
    }
    class Write:Test, Test2
    {
        public void Print()
        {
            Console.WriteLine("Implcit implementation");
        }
        void Test.Print()
        {
            Console.WriteLine("Testing TEST1 interface print method *explicit*");
        }

        void Test2.Print()
        {
            Console.WriteLine("Testing the TEST2 interface print method *explicit*");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

            Write writer = new Write();
            Test t1 = new Write();
            Test2 t2 = new Write();
            writer.Print();
            t1.Print();
            t2.Print();
            Console.ReadLine();
        }
    }

Leave a comment