In C#, is there a way to overload comparison operators such as ==, =< or> on a user-defined object?
Similar to how yo can write "string"=="string" instead of "string".Equals("string")
I know you can define the CompareTo and Equals functions but I was wondering if there was a shortcut.
You can override the
==operators in C# by implementing a function with the following signature in the desiredclass:public static bool operator ==(YourClass a, YourClass b) { }The same applies to
<=and>operators.By overriding
==you must also override!=, and is recommended to overload theEqualsandGetHashcodefunctions.For more info, read:
Operator Overloading Tutorial
Guidelines for Overloading Equals() and Operator == (C# Programming Guide)