Reputation: 31
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.
Upvotes: 2
Views: 209
Reputation: 1135
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:
Guidelines for Overloading Equals() and Operator == (C# Programming Guide)
Upvotes: 5
Reputation: 3925
Simple example:
class Foo
{
public int Id { get; set; }
public static bool operator ==(Foo first, Foo second)
{
return first.Id == second.Id;
}
public static bool operator !=(Foo first, Foo second)
{
return first.Id != second.Id;
}
}
You should also override Equals and GetHashCode
Upvotes: 4