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> ?
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>.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With