Polymorphic Equality

Clean Code, Test Driven Development, Testing, C#, .Net, Object Oriented Design


The default generation of Equality members provided by Resharper let you choose three different implementations when overriding the “Equals” method in a class (Alt+Insert -> Equality Members):

The default choice is “Exactly the same type as ‘this’” which IS NOT polymorphic. I mean, subtypes of that class will be considered not equal regardless of the values:

equalityGeneration

On line 8 it compares the types which in the case of subtypes will be different thus returning false.

I didn’t pay attention to this detail today and for some reason assumed that the comparison was going to work for subtypes. Lesson learned: always pay attention to generated code!

This is the generated code to consider subtypes equal:

And this is yet another implementation that works:

The other lesson learned is that overriding the Equals method in the child class when the base class already overrides it, increases the complexity too much. The code is hard to follow and surprising. It increases the coupling between the child class and the parent.

Avoid overriding the equality members in class hierarchies if you can.

Originally published in Carlos Blé's blog.