O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required