How does comparison operator works with null int?

Ron5504 picture Ron5504 · Apr 3, 2013 · Viewed 74.4k times · Source

I am starting to learn nullable types and ran into following behavior.

While trying nullable int, i see comparison operator gives me unexpected result. For example, In my code below, The output i get is "both and 1 are equal". Note, it does not print "null" as well.

int? a = null;
int? b = 1;

if (a < b)
    Console.WriteLine("{0} is bigger than {1}", b, a);
else if (a > b)
    Console.WriteLine("{0} is bigger than {1}", a, b);
else
    Console.WriteLine("both {0} and {1} are equal", a, b);

I was hoping any non-negative integer would be greater than null, Am i missing something here?

Answer

nkvu picture nkvu · Apr 3, 2013

According to MSDN - it's down the page in the "Operators" section:

When you perform comparisons with nullable types, if the value of one of the nullable types is null and the other is not, all comparisons evaluate to false except for !=

So both a > b and a < b evaluate to false since a is null...