Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading operator < in C# [duplicate]

I have following code:

public class Foo
{
    public static bool operator<(Foo l, Foo f)
    {
        Console.WriteLine("Foo!");
        return false;
    }
    //public static bool operator>(Foo l, Foo f)
    //{
    //    return f < l;
    //}
}

Compiler tells about error with message:

The operator 'Program.Foo.operator <(Program.Foo, Program.Foo)' requires a matching operator '>' to also be defined

It seems very weird for me. Why should I overload operator> ?

like image 625
LmTinyToon Avatar asked May 03 '26 01:05

LmTinyToon


2 Answers

Because that operator comes in pairs (like == and !=). It expects you to implement both to make sure you don't accidentally forget about it. If you say that < behaves differently, > should too, hence you are forced to overload it too.

As MSDN says:

User-defined types can overload the < operator. If a type overloads the "less than" operator <, it must also overload the "greater than" operator >.

like image 134
Patrick Hofman Avatar answered May 04 '26 15:05

Patrick Hofman


I can speculate that the reason is because of mathematical properties of inequality operators. https://en.wikipedia.org/wiki/Inequality_(mathematics)

> is inverse of <

It would not be surprising if compiler assumes those properties and is allowed to swap one for another. And even if compiler is not allowed to do that - resulting code would be unmanageable.

E.g. take refactoring tools as an example - inverting operators is a fairly common functionality in those.

like image 30
bushed Avatar answered May 04 '26 16:05

bushed