#404 – Equals Method vs. == Operator for Value Types

In C#, you can compare two objects for equality by using the Equality operator (==) or by calling the Equals method.  For built-in value types, the default behavior checks for value equality, or equivalence.

            int i1 = 42;
            int i2 = 42;

            bool check1 = i1 == i2;      // true
            bool check2 = i1.Equals(i2);  // true
            bool check3 = int.Equals(i2, i2);  // true

For the predefined value types (e.g. int, float):

  • The Equals method performs a value equality check
  • The == operator resolves to the CIL ceq instruction, which does a strict identity check

For user-defined struct types:

  • The Equals method implementation performs a value equality check by comparing each field of the struct (using reflection).  You can (and should) override Equals to provide an implementation specific to the struct.
  • The == operator is undefined, unless you override it in the struct.
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: