Advertisement
Intermediate C#, Indexers & Operator Overloading

How do you overload comparison operators like < and >, and what consistency rule must they maintain relative to Equals()?

Short answer

Overload ' ' as static operator methods, and their logic must be CONSISTENT with any overloaded '==' and Equals() — specifically, if a.Equals(b) is true, then neither a b should also be true, maintaining a coherent total ordering that doesn't contradict equality.

Save C# mock interview
Advertisement
AModel answer
Overload '<' and '>' as static operator methods, and their logic must be CONSISTENT with any overloaded '==' and Equals() — specifically, if a.Equals(b) is true, then neither a < b nor a > b should also be true, maintaining a coherent total ordering that doesn't contradict equality.
public struct Money : IComparable<Money> {
  public decimal Amount;
  public static bool operator <(Money a, Money b) => a.Amount < b.Amount;
  public static bool operator >(Money a, Money b) => a.Amount > b.Amount;
  public int CompareTo(Money other) => Amount.CompareTo(other.Amount); // must agree with < and >
}
Real-world example
Allowing natural comparison syntax (a < b) for a Money or custom numeric type used in sorting and range checks.
Likely follow-ups
  • If you overload '<', does C# require you to also overload '>' — and what other operator pairing rules exist?
Related topics