Search code examples
c#operator-overloadingprinciples

C# overloading operator==: Return something else than bool


I'm writing a class library to solve non-linear equations using newton's method. I stumbled across operator-overloading and thought about overloading the ==-Operator. Something like expression1 == expression2 returns the solution as a Constant, which is basically a wrapper-class of System.Double:

public static Constant operator ==(Derivable d1, Derivable d2)
{
    return d1.Equal(d2);
}

Although it compiles perfectly fine and works, I was asking myself if it would ever be a reasonable design-choice to overload the ==-Operator to return something else than the equality of two objects as a bool, especially because you also have to overload the !=-Operator. Is this bad practice and should I rather just use my method Equal?


Solution

  • As a fellow developer, I would suggest not overriding the == Operator (C# Reference).

    For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings.

    I can't imagine a scenario where you would want to override this behavior. If you are working with classes then you could override the Object.Equals Method (Object).

    If you are working with other developers this could be very confusing.