Overloading Equals in Value Types

Problem
You want to know how to handle the Equals method when implementing a structure.

Solution
When implementing value types like structures, you’ll want to overload the Equals method. Define both instance and static versions and make them take typed arguments.

Comments
Typed versions of the Equals method improve performance by avoiding boxing. The ValueType.Equals method, which all value types inherit, is inefficient. That’s because the base method uses reflection to compare all fields. Additionally, if you override the Equals method, you should override the GetHashCode method along with the == and != operators.

Example

public struct Point {
    // Properties in a real-world app.
    public readonly double xAxis;
    public readonly double yAxis;

    public Point(double x, double y) {
        this.xAxis = x;
        this.yAxis = y;
    }

    // Strongly-typed version of the instance method.
    public bool Equals(Point point) {
        return this.xAxis == point.xAxis && this.yAxis == point.yAxis;
    }

    // Strongly-typed version of the static method.
    public static bool Equals(Point pointOne, Point pointTwo) {
        return pointOne.xAxis == pointTwo.xAxis && pointOne.yAxis == pointTwo.yAxis;
    }
}

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