Search code examples
c#equalsshort-circuiting

Return a variable as soon as it is set to a certain value. Equality overloading


I am overloading the Equality method for value comparison and was wondering if there is a clean way to return false as soon as one of the value comparisons returns false. For example, here is the basic idea:

public class MyClass
{
    private int _valOne;
    private int _valTwo;
    private int _valThree;

    public MyClass(int valOne, int valTwo, int valThree)
    {
        _valOne = valOne;
        _valTwo = valTwo;
        _valThree = valThree;
    }

    public override bool Equals(object obj)
    {
        // If the object is null return false
        if (obj == null)
        {
            return false;
        }

        // If the object is not of MyClass type return false
        MyClass myClass = obj as MyClass;
        if (myClass == null)
        {
            return false;
        }

        // Now compare all the field values
        bool areEqual = false;
        areEqual = (this._valOne == myClass._valOne);
        areEqual = (this._valTwo == myClass._valTwo);
        areEqual = (this._valThree == myClass._valThree);

        return areEqual;
    }
}

Say the _valOne's do not equal. The most efficient way to compare is to return false as soon as it is known two values are not equal. Something like the following...

        // Now compare all the field values
        bool areEqual = false;

        areEqual = (this._valOne == myClass._valOne);
        if (!areEqual)
        {
            return false;
        }

        areEqual = (this._valTwo == myClass._valTwo);
        if (!areEqual)
        {
            return false;
        }

        areEqual = (this._valThree == myClass._valThree);

        return areEqual;

So now after the comparison of the _valOnes no more value comparisons are made. This seems very repetitive, clunky, and (most importantly) horrible for readability. I want to know if there is any way this code can be reduced to the same effect in a clean way without the use of the && operator.


Solution

  • Use an and condition:

    areEqual = (this._valOne == myClass._valOne) 
        && (this._valTwo == myClass._valTwo) 
        && (this._valThree == myClass._valThree);
    

    && implements short-circuiting by default.