I have a C# type for which it makes logical sense to compare for equality with int. Call this type Number
.
However, I can't make Equals symmetric, because I can't change Int32.Equals(object other)
. So, should I permit the asymmetric equality, like this:
Number numberThree = new Number(3);
int intThree = 3;
bool equal;
equal = numberThree.Equals(intThree); // equal is true
equal = intThree.Equals(numberThree); // equal is false
Or should I just only allow equality if the types match as well as the numeric value?
No. It violates the contract of Object.Equals
:
The following statements must be true for all implementations of the
Equals(Object)
method. In the list,x
,y
, andz
represent object references that are not null.
- ...
x.Equals(y)
returns the same value asy.Equals(x)
.
Anything using Equals
should be able to depend on that - so violating it could generate some really odd effects. Imagine if Dictionary<,>.ContainsKey
called key.Equals(candidateEntry.Key)
but the indexer called candidateEntry.Key.Equals(key)
... you might see a key as existing, but not be able to fetch the entry... or vice versa. Or maybe it will work in one implementation of Dictionary<,>
, but not in a subsequent release (or not on Mono, etc).