Why are comparison operators not automatically overloaded with IComparable?

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;

// And for equality:
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?

+4
2

IComparable, , <, > == - CompareTo, ?

.

. , #.

http://www.informit.com/articles/article.aspx?p=2425867

?

. , , , , , . , .

. , .

, , Roslyn Github , , -.

+9

Roslyn Github. :

  • -: - , "" .
  • : == , CompareTo, .

Nuget, , OP, . https://www.nuget.org/packages/Exts.Comparisions.Classes.Operators/

0

Source: https://habr.com/ru/post/1656731/


All Articles