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

September 9, 2008 on 9:14 pm | In Uncategorized | No Comments

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");
               case 1:
                  Console.WriteLine("i > j");
               case 0:
                  Console.WriteLine("i == j");

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


Powered by WordPress with Pool theme design by Borja Fernandez.
Text © Marcin Kawalerowicz. Hosting CODEFUSION.