C#: Never Test For NaN With Equality Test

Let's write a simple program to test. To get a NaN, we do a 0/0 and store it in num. First of all, the divisor has to be a float-point type because DivideByZeroException shall be thrown for integer or decimal zero divisor. Note: Non-zero number divided by zero (float) gives an infinity number. In our program, we compare num to NaN and next, compare num to itself and then, we compare 2.0 to NaN. Lastly, we check if num is NaN with Double.IsNaN().

double num = 0.0 / 0.0; // Result of 0 divided by 0 is a NaN

Console.WriteLine("num == NaN is {0}", (num == double.NaN));
Console.WriteLine("num == num is {0}", (num == num));
Console.WriteLine("2.0 == NaN is {0}", (2.0 == double.NaN));
Console.WriteLine("double.IsNaN(num) is {0}", double.IsNaN(num));

This is the output. All the 3 NaN comparisons return False while IsNaN() check on num returns True. This is exactly the same behaviour with C++. The advice for this tip is never test for NaN with equality test, use IsNaN() instead.

num == NaN is False
num == num is False
2.0 == NaN is False
double.IsNaN(num) is True

If reader is interested to know more about floating-point format, read my Succinct Guide to Floating Point Format For C++ and C# Programmers.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: