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.

3
  • You can always overload the operators for your class. Commented Nov 15, 2012 at 21:45
  • possible duplicate of How to best implement Equals for custom types? Commented Nov 15, 2012 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. Commented Nov 15, 2012 at 22:04

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

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 Thanks! I didn't know. I'll make up to it!
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.