I am stuck trying to find out why these two operations return different values:
Double.NaN == Double.NaNreturnsfalseDouble.NaN.Equals(Double.NaN)returnstrue
I have the answer to the first part but not the second and not to “why are these two comparisons returning different values”
The reason for the difference is simple, if not obvious.
If you use the equality operator
==, then you’re using the IEEE test for equality.If you’re using the
Equals(object)method, then you have to maintain the contract ofobject.Equals(object). When you implement this method (and the correspondingGetHashCodemethod), you have to maintain that contract, which is different from the IEEE behaviour.If the
Equalscontract was not upheld, then the behaviour of hash tables would break.If
!double.NaN.Equals(double.NaN), you’d never get your value out of the dictionary!If the previous sentence does not make sense, then understand that the mechanics of hashing (used in
Dictionary<T,U>,HashSet<T>, etc) use both theobject.Equals(object)andobject.GetHashCode()methods extensively, and rely upon guarantees of their behaviour.