#411 – Overriding the Equals Method for a Value Type

A user-defined struct inherits from System.ValueType implicitly.

System.ValueType includes a default implementation of the Equals method that compares the individual fields of two instances of the type, to determine if the instances are equivalent.  It uses reflection to determine which fields to compare and compares both public and private fields.  (This includes the values of auto-implemented properties, which use an automatically generated private backing field).

You should generally override the Equals method in a user-defined struct, comparing all of the fields directly.  This is typically faster than the default implementation, since your method does not need to use reflection.

If you are also overloading the == operator, you can define Equals in terms of the operator.

        public override bool Equals(object obj)
        {
            return ((obj is PersonHeight) && ((PersonHeight)obj == this));
        }

        public static bool operator ==(PersonHeight ph1, PersonHeight ph2)
        {
            return (ph1.Feet == ph2.Feet) && (ph1.Inches == ph2.Inches);
        }
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: