#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.


#401 – Every Object Inherits an Equals Method

Every type inherits directly or indirectly from System.Object, so each has an Equals method.  This includes both value types (which inherit from System.ValueType) and reference types (which inherit from System.Object).

            public virtual bool Equals(Object object);

The Equals method returns true if the object passed in to the method is equal to the object on which the method was called.

System.Object includes a default implementation of the Equals method that :

  • For value types, returns true if the underlying values are the same (even though there are two copies of the value)
  • For reference types, returns true if the references refer to the exact same object in memory
            float f1 = 10.2f;
            float f2 = 10.2f;
            bool sameFloat = f1.Equals(f2);     // true - same value

            Dog kirby = new Dog("Kirby", 13);
            Dog kirby2 = new Dog("Kirby", 13);
            bool sameDog = kirby.Equals(kirby2);   // false - two different objects

            Dog kirby3 = kirby;
            sameDog = kirby3.Equals(kirby);    // true - two references to same object