user809736
user809736

Reputation: 31

C# Object Comparisons

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

Answers (2)

LMB
LMB

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:

Operator Overloading Tutorial

Guidelines for Overloading Equals() and Operator == (C# Programming Guide)

Upvotes: 5

trydis
trydis

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

Related Questions