I have been reading about how best to override the equals method when dealing with subclasses and here I have found quite a few posts. They recommend different ways of implement
The base class contract should specify one of two approaches: either it should declare that no derived-class object should consider itself to any other object that is not of the exact same class, or else it should specify that every derived-class object should be convertible to a canonical form defined by the base-class contract, and two immutable objects should be considered equivalent if their canonical forms would match.
An example of the latter situation would be an ImmutableSquareFloatMatrix base class with methods int GetSize()
and float GetCell(int row, int column)
. A common implementation would have an array of (size*size) float values in it, but one could also have e.g. ZeroMatrix
and IdentityMatrix
classes whose only field specified the size, a ConstantMatrix
class with a field specifying the size and a field specifying a value which should be returned for every cell, a DiagonalMatrix
class with a single-dimensional array just containing items for the diagonal (the GetCell
method would return zero for everything else), etc.
Given two instances of classes derived from ImmutableSquareFloatMatrix
, it would be possible to compare them by comparing their sizes and then comparing all the values therein, but that would in many cases be inefficient. If either of the objects being compared "knows" about the other object's type, it may be possible to improve efficiency enormously. If neither object knows about the other, falling back to a default comparison method may be slow, but would yield correct results in any case.
A workable approach to handle that situation may be to have the base type implement an equals2
method, which return 1 if its special knowledge of the other object meant it could tell it was equal, -1 if it could tell it was not equal, or 0 if it couldn't tell. If either type's equals2
method knows they're unequal, they're unequal. Otherwise, if either knows they're equal, they're equal. Otherwise, test equality using cell-by-cell comparison.