Overriding the Equals Method

Problem
You want to know when to override the Equals method.

Solution
Override the Equals instance method when two objects are deemed equal even if they aren’t the same instance of the type.

Comments
You never want the Equals method to throw an exception. You want it to return false if the argument is a null object reference or a different type.

Example

/* This class redefines the Equals method so that two
 * Triangle instances are considered equal when the
 * value of their Side property is the same.
 */
public class Triangle {
    // In the real world, this would be a property.
    public double Side;

    public override bool Equals(object obj) {
        if ( this == obj ) {
            // The argument is the same object as this.
            return true;
        }
        else if ( obj == null || obj.GetType() != this.GetType() ) {
            // The argument is null or of a different type.
            return false;
        }
        else {
            Triangle other = (Triangle) obj;
            return (this.Side == other.Side);
        }
    }
}

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s