IComparable
exposes CompareTo
. <
and >
must be overloaded separately:
class Foo : IComparable<Foo>
{
private static readonly Foo Min = new Foo(Int32.MinValue);
private readonly int value;
public Foo(int value)
{
this.value = value;
}
public int CompareTo(Foo other)
{
return this.value.CompareTo((other ?? Min).value);
}
public static bool operator <(Foo a, Foo b)
{
return (a ?? Min).CompareTo(b) < 0;
}
public static bool operator >(Foo a, Foo b)
{
return (a ?? Min).CompareTo(b) > 0;
}
}
I edited the code so that it does not fail when comparing against null
. To keep it brief I used a shortcut that works unless value
is Int32.MinValue
for a proper Foo
. Strictly speaking you'd have to check for null
explicitly to get the contract right:
By definition, any object compares greater than (or follows) null, and
two null references compare equal to each other.
Besides, implementing IComparable<T>
means that CompareTo(T value)
takes a parameter of T
. Therefore MyCalendar : IComparable<MyCalender>
should implement a method CompareTo(MyCalendar other)
rather than PersianDate
(or implement IComparable<PersianDate>
).