3.9. Improving the Performance of a Structure’s Equals Method

Problem

You need to provide a better performing Equals method than the default Equals method on a structure. The default implementation of Equals on a ValueType uses reflection to compare the fields of two ValueTypes, resulting in poor performance. Note that this recipe does not hold true for classes; although the same techniques apply if you want to overload the Equals method in a class.

Solution

Override the Equals method. When this method is overridden, you must also override the GetHashCode method:

public struct Line
{
    public Line(int startX, int startY, int endX, int endY)
    {
        x1 = startX;
        x2 = endX;
        y1 = startY;
        y2 = endY;
    }

    private int x1;
    private int y1;
    private int x2;
    private int y2;

    public override bool Equals(object obj)
    {
        bool isEqual = false;

        if (obj == null || (this.GetType( ) != obj.GetType( ))) 
        {
            isEqual = false;
        }
        else
        {
            Line theLine = (Line)obj;
            isEqual = (this.x1 == theLine.x1) && 
                      (this.y1 == theLine.y1) && 
                      (this.x2 == theLine.x2) && 
                      (this.y2 == theLine.y2);
        }
        return (isEqual);

    }

    public override int GetHashCode( )
    {
        return (x1+109*(x2+113*(y1+127*y2)));
    }
}

In addition, a strongly typed Equals method can be added to further streamline this operation:

public bool Equals(Line lineObj)
{
    bool isEqual = (this.x1 == lineObj.x1) && 
                   (this.y1 == lineObj.y1) && 
                   (this.x2 == lineObj.x2) && 
                   (this.y2 == lineObj.y2);

    return (IsEqual);
}

In this recipe, we chose a Line structure arbitrarily. However, your focus should ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.