Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Object Comparisons

Tags:

c#

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.

like image 601
user809736 Avatar asked Jun 25 '26 02:06

user809736


1 Answers

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)

like image 164
LMB Avatar answered Jun 26 '26 15:06

LMB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!