Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best practices for implementing the == operator for a class in C#?

While implementing an == operator, I have the feeling that I am missing some essential points.
Hence, I am searching some best practices around that.
Here are some related questions I am thinking about:

  • How to cleanly handle the reference comparison?
  • Should it be implemented through a IEquatable<T>-like interface? Or overriding object.Equals?
  • And what about the != operator?

(this list might not be exhaustive).

like image 784
remio Avatar asked Oct 06 '09 11:10

remio


3 Answers

I would follow Microsoft's Guidelines for Overloading Equals() and Operator ==.

edit: Microsoft's guidelines contain this important remark, which seems to confirm Henk's answer:

By default, the operator == tests for reference equality by determining if two references indicate the same object, so reference types do not need to implement operator == in order to gain this functionality. When a type is immutable, meaning the data contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. Overriding operator == in non-immutable types is not recommended

like image 78
Wim Coenen Avatar answered Oct 18 '22 02:10

Wim Coenen


Each time you implement the == operator, be sure to also implement !=, IEquatable<T> and to override Object.Equals() and Object.GetHashCode() for consistency for the user of your class.

Considering a class, here's my usual implementation:

    public bool Equals(MyClass other) {
        if (ReferenceEquals(other, null))
            return false;
        if (ReferenceEquals(other, this))
            return true;
        return // your equality code here
    }

    public override bool Equals(object obj) {
        return Equals(obj as MyClass);
    }

    public override int GetHashCode() {
        return // your hash function here
    }

    public static bool operator ==(MyClass left, MyClass right) {
        return Equals(left, right);
    }

    public static bool operator !=(MyClass left, MyClass right) {
        return !(left == right);
    }
like image 32
Julien Lebosquain Avatar answered Oct 18 '22 01:10

Julien Lebosquain


  • If you implement ==, override .Equals and . GetHashCode
  • implement != as well
  • Check for null references using object.ReferenceEquals otherwise the operator will recurse
like image 23
dkackman Avatar answered Oct 18 '22 03:10

dkackman