2

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.

joce
  • 9,624
  • 19
  • 56
  • 74
user809736
  • 31
  • 3
  • possible duplicate of [How to best implement Equals for custom types?](http://stackoverflow.com/questions/567642/how-to-best-implement-equals-for-custom-types) – NotMe Nov 15 '12 at 21:46
  • The proposed duplicate is clearly not a duplicate of this question; he's asking how to overload operators, not what sensible implementations of them are. – Servy Nov 15 '12 at 22:04
  • You can always [overload the operators](http://msdn.microsoft.com/en-us/library/aa288467%28v=vs.71%29.aspx) for your class. – Justin Niessner Nov 15 '12 at 21:45

2 Answers2

5

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)

LMB
  • 1,137
  • 7
  • 23
  • Link only answers are not considered acceptable on Stack Overflow. If you're going to post links to content you should also explain the link, quote a relevant section, and or summarize enough of the content such that the question is answered entirely within your post and following the link is just optional, not required to see the solution. – Servy Nov 15 '12 at 22:02
  • @Servy Thanks! I didn't know. I'll make up to it! – LMB Nov 15 '12 at 23:05
4

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

trydis
  • 3,905
  • 1
  • 26
  • 31