When a class IComparable, we know everything to overload operators <, >and ==because of functionality CompareTo, right? Then why aren't they overloaded automatically?
Take a look at the example below:
public class MyComparable : IComparable<MyComparable>
{
public int Value { get; }
public MyComparable(int value) { Value = value; }
public int CompareTo(MyComparable other) => Value.CompareTo(other.Value);
}
I was wondering why something like this would not work by default:
MyComparable obj1 = new MyComparable(1),
obj2 = new MyComparable(2);
if (obj1 < obj2) { }
We know that obj1 < obj2 == truedue to our implementation CompareTo, but since the operator is <not overloaded, this will not work. (I know that obj1.CompareTo(obj2) < 0will give the desired result, but in most cases it will be less obvious.)
Only when I add the code below to the class will it work as I expected:
public static bool operator <(MyComparable x, MyComparable y) => x.CompareTo(y) < 0;
public static bool operator >(MyComparable x, MyComparable y) => x.CompareTo(y) > 0;
public static bool operator !=(MyComparable x, MyComparable y) => !(x == y);
public static bool operator ==(MyComparable x, MyComparable y)
{
if (ReferenceEquals(x, y)) return true;
if (((object) x == null) || ((object) y == null)) return false;
return x.CompareTo(y) == 0;
}
, IComparable?