TIL: Double.Equals works with Double.NaN values

By | 2019-10-02

The .NET standard defines that the double value of NaN (Double.NaN) will never be equal to any other Double value, including itself.
In other words:

double first = Double.NaN;
double second = Double.NaN;
bool equal = first == second; // false;

However this does not hold for Double.Equals. Double.Equals checks for object 'Identity' and not object 'Equality'.

double first = Double.NaN;
double second = Double.NaN;
bool equal = first.Equals(second); // true;

This is in general a nice thing if you have a generic methods which rely on object equality. Object.Equals will work even for Double and Single types.

Leave a Reply

Your email address will not be published. Required fields are marked *