What null smaller than 0? Adventures with nullable types in .NET

Lets say we have two nullable integers like this:

int? i = null;
int? j = 0;


Is null smaller than 0

Console.WriteLine(i < j);


False – no it is not.
So probably null is greater than 0

Console.WriteLine(i > j);


False – no it is not greater as well.
All right! So null is equal 0. It has to be, JIT has no other choice, right?

Console.WriteLine(i == j);

Well False too! This two little fellows are not equal too. What? Is it raining frogs and we about to experience Armageddon?
No! We have to use Nullable.Compare() and we will by back in normal world:

switch (Nullable.Compare(i, j))
        {
               case -1:
                  Console.WriteLine("i < j");
              break;
               case 1:
                  Console.WriteLine("i > j");
              break;
               case 0:
                  Console.WriteLine("i == j");
              break;
        }


0 is a little more than null. null is less than 0. null equals null and 0 equals 0.
Uff!

Leave a Reply

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