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.
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.
class Point : IComparable<Point>
And in last here the two methods that are overloading < and > Operators.
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.