var testObject1 = new RecursiveEquals();
var testObject2 = new RecursiveEquals();
//// These will work
testOutcome = (object)testObject1 == testObject2;
testOutcome = (object)testObject1 != testObject2;
//// These all crash
// testOutcome = testObject1 == testObject2;
// testOutcome = testObject1 != testObject2;
// testOutcome = testObject1.Equals(testObject2);
// testOutcome = ((object)testObject1).Equals(testObject2);
public override bool Equals(object other)
// this would typically be less obvious
public static bool operator ==(RecursiveEquals left, object right)
public static bool operator !=(RecursiveEquals left, object right)
Casting p as a less derived object will NOT invoke the less derived implementation of the method.
I've tried to make the recursive .Equals call obvious enough to illustrate what is a more subtle common problem when people override it. In this answer, I am focusing on the point that casting the object does not change the method implementation which is used.
Unless casting to an interface type which is implemented explicitly in the Class's hierarchy, this will invoke the most derived definition. To not work this way would violate polymorphism principles.
This will work for operator overloads in .NET as you are doing. Until I started researching this answer, I was not aware that operator overloads do NOT actually use the most derived implementation. I personally find this result surprising.