Should I allow asymmetric equalities?
I have a C # type for which it makes logical sense to compare for equality to int. Call this type Number
.
However, I cannot make Equals symmetric because I cannot change Int32.Equals(object other)
. So, should asymmetric equality be allowed like:
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 allow equality if the types are the same as well as a numeric value?
source to share
Not. He violates the contract Object.Equals
:
The following statements must be true for all method implementations
Equals(Object)
. In a listx
,y
andz
represent object references that are not null.
- ...
x.Equals(y)
returns the same value asy.Equals(x)
.
Anything that uses Equals
should be able to depend on it - so breaking it can cause some really strange effects. Imagine, if Dictionary<,>.ContainsKey
called key.Equals(candidateEntry.Key)
, but the pointer is named candidateEntry.Key.Equals(key)
... you can see the key as existing, but you can't get the entry ... or vice versa. Or perhaps it will work in one implementation Dictionary<,>
, but not in a later version (or not in Mono, etc.).
source to share