Partager via


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

In C#, there are two different kinds of equality: reference equality and value equality. Value equality is the commonly understood meaning of equality: it means that two objects contain the same values. For example, two integers with the value of 2 have value equality. Reference equality means that there are not two objects to compare. Instead, there are two object references, both of which refer to the same object. This can occur through simple assignment, as shown in the following example:

System.Object a = new System.Object();
System.Object b = a;
System.Object.ReferenceEquals(a, b);  //returns true

In this code, only one object exists, but there are multiple references to that object: a and b. Because they both refer to the same object, they have reference equality. If two objects have reference equality, then they also have value equality, but value equality does not guarantee reference equality.

To check for reference equality, use ReferenceEquals. To check for value equality, use Equals or Equals.

Overriding Equals

Equals is a virtual method, enabling any class to override its implementation. Any class that represents a value, essentially any value type, or a set of values as a group, such as a complex number class, should override Equals. If the type implements IComparable, it should override Equals.

The new implementation of Equals should follow all the guarantees of Equals:

  • x.Equals(x) returns true.

  • x.Equals(y) returns the same value as y.Equals(x).

  • if (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true.

  • Successive invocations of x.Equals(y) return the same value as long as the objects referenced by x and y are not modified.

  • x.Equals(null) returns false.

The new implementation of Equals should not throw exceptions. It is recommended that any class that overrides Equals also override System.Object.GetHashCode. It is also recommended that in addition to implementing Equals(object), any class also implement Equals(type) for their own type, to enhance performance. For example:

class TwoDPoint : System.Object
{
    public readonly int x, y;

    public TwoDPoint(int x, int y)  //constructor
    {
        this.x = x;
        this.y = y;
    }

    public override bool Equals(System.Object obj)
    {
        // If parameter is null return false.
        if (obj == null)
        {
            return false;
        }

        // If parameter cannot be cast to Point return false.
        TwoDPoint p = obj as TwoDPoint;
        if ((System.Object)p == null)
        {
            return false;
        }

        // Return true if the fields match:
        return (x == p.x) && (y == p.y);
    }

    public bool Equals(TwoDPoint p)
    {
        // If parameter is null return false:
        if ((object)p == null)
        {
            return false;
        }

        // Return true if the fields match:
        return (x == p.x) && (y == p.y);
    }

    public override int GetHashCode()
    {
        return x ^ y;
    }
}

Any derived class that can call Equals on the base class should do so before finishing its comparison. In the following example, Equals calls the base class Equals, which checks for a null parameter and compares the type of the parameter with the type of the derived class. That leaves the implementation of Equals on the derived class the task of checking the new data field declared on the derived class:

class ThreeDPoint : TwoDPoint
{
    public readonly int z;

    public ThreeDPoint(int x, int y, int z)
        : base(x, y)
    {
        this.z = z;
    }

    public override bool Equals(System.Object obj)
    {
        // If parameter cannot be cast to ThreeDPoint return false:
        ThreeDPoint p = obj as ThreeDPoint;
        if ((object)p == null)
        {
            return false;
        }

        // Return true if the fields match:
        return base.Equals(obj) && z == p.z;
    }

    public bool Equals(ThreeDPoint p)
    {
        // Return true if the fields match:
        return base.Equals((TwoDPoint)p) && z == p.z;
    }

    public override int GetHashCode()
    {
        return base.GetHashCode() ^ z;
    }
}

Overriding Operator ==

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.

Overloaded operator == implementations should not throw exceptions. Any type that overloads operator == should also overload operator !=. For example:

//add this code to class ThreeDPoint as defined previously
//
public static bool operator ==(ThreeDPoint a, ThreeDPoint b)
{
    // If both are null, or both are same instance, return true.
    if (System.Object.ReferenceEquals(a, b))
    {
        return true;
    }

    // If one is null, but not both, return false.
    if (((object)a == null) || ((object)b == null))
    {
        return false;
    }

    // Return true if the fields match:
    return a.x == b.x && a.y == b.y && a.z == b.z;
}

public static bool operator !=(ThreeDPoint a, ThreeDPoint b)
{
    return !(a == b);
}

Note

A common error in overloads of operator == is to use (a == b), (a == null), or (b == null) to check for reference equality. This instead results in a call to the overloaded operator ==, causing an infinite loop. Use ReferenceEquals or cast the type to Object, to avoid the loop.

See Also

Reference

Statements, Expressions, and Operators (C# Programming Guide)
Operators (C# Programming Guide)
Overloadable Operators (C# Programming Guide)
== Operator (C# Reference)
() Operator (C# Reference)

Concepts

C# Programming Guide