#403 – Equals Method vs. == Operator for Reference Types

In C#, you can compare two objects for equality by using the Equality operator (==) or by calling the Equals method.  In both cases, the default behavior for reference types is to check for reference equality, or identity.

    bool sameDog = yourDog.Equals(myDog);
    bool sameDog2 = yourDog == myDog;
    bool sameDog3 = Dog.Equals(yourDog, myDog);

By default, for a reference type, these mechanisms behave exactly the same way, implementing a reference equality check.  Under the covers, they are a bit different:

  • The Equals method is an instance method of the System.Object class.  It does some checks for null, but then uses the == operator in the default implementation.  It is a virtual method that you can override.
  • The == operator resolves to the CIL ceq instruction, which does a strict identity check.  You can override the == operator, in which case a new method named op_Equality is defined/called.

You can override Equals and the == operator independently.

Advertisements