Click here to Skip to main content
15,911,035 members
Please Sign up or sign in to vote.
4.67/5 (3 votes)
I'm very new to C# Language. C# provides two similar Interfaces named IComparable Interface and IComparer Interface for comparison.
While working on it, I found two uses of IComparable<t> in C# yet.
1- Sorting custom collections of objects
2- Overloading operators like < , > , <= , >= etc.
have a look at the code where I'm using IComparable<point> to overload < and > operators.
C#
public int CompareTo(Point other)
       {
           if (this.X > other.X && this.Y > other.Y)
           {
               return 1;
           }
           if (this.X < other.X && this.Y < other.Y)
           {
               return -1;
           }
           else
           {
               return 0;
           }
       }

This is the Point class which is implementing this interface.
C#
class Point : IComparable<Point>

And in last here the two methods that are overloading < and > Operators.
C#
public static bool operator < (Point p1 , Point p2)
        {
            return (p1.CompareTo(p2) < 0);
        }
        public static bool operator >(Point p1, Point p2)
        {
            return (p1.CompareTo(p2) > 0);
        }

Apart from these long lines of code and text , My question is very simple. Is it necessary to use this interface always to sort the objects and overloading such operators which uses for comparison etc.

What I have tried:

I searched around on internet and on many different websites, everyone is discussing
1- What is IComparable<t> in C#
OR
2- How to use IComparable<t> in C#
Nobody is discussing
> why need this in real time scenarios? still we have to write extra line of code to implementing this interface rather than using our custom methods which simple to write for small classes.
Posted
Updated 10-Apr-17 19:55pm
v3
Comments
CHill60 10-Apr-17 9:17am    
Imagine you have a [car] class and want to compare which cars are "better". Doing something like If [Rolls Royce] > [Austin Mini] only makes sense if you have defined what > means in terms of a [car]

1 solution

Interfaces are both a contract and a "membership club": when you add an interface to your class, you are applying for "membership of the club" and the admission fee is the contract which you must implement in order to join. This means implementing the properties, methods, and such like that the interface specifies.

When you join the club, you get the benefits of membership - in the case of IComparable that means that the Sort method can work without you having to do anything else: Sorting Lists using IComparable and IComparer Interface in .NET[^] have a read - it explains it all pretty well.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900