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 desired class:
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 the Equals and GetHashcode functions.
For more info, read:
Operator Overloading Tutorial
Guidelines for Overloading Equals() and Operator == (C# Programming Guide)
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