#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: