Francesco's blog

 Wednesday, December 28, 2005

Today I spent a few minutes trying to understand the behavior of nullable types in C#, in particular how comparison operators evaluate their result. An asimmetry exists between the == and != operators and all the other comparison operators. In fact, the equal and not-equal operators work perfectly even when the two operands are both null, as in the following code:

int? x1 = null;
int? x2 = null;
Console.WriteLine(x1 == x2);    // => True
Console.WriteLine(x1 != x2);     // => False

The remaining comparison operators, however, don't deal with null values in the same correct way. If either operand is null, these operators always return false. This inconsistent behavior brings to weird situations, in which two values can satisfy the "equal to" relation but not the "equal to or greater than" relation:

int? x1 = null;
int? x2 = null;
Console.WriteLine(x1 == x2);    // => True
Console.WriteLine(x1 >= x2);    // => False

To compare nullable values in a coherent way, you should use the Nullable.Compare static method, which considers null as less than any other value:

switch (Nullable.Compare(d1, d2))
{
  
case -1:
     
Console.WriteLine("d1 is null or is less than d2");
     
break;
  
case 1:
     
Console.WriteLine("d2 is null or is less than d1");
     
break;
  
case 0:
     
Console.WriteLine("d1 and d2 have same value or are both null.");
     
break;
}

In some cases, you can compare two nullable values by using the lowest value in the range in lieu of the "unknown" state, as in:

Console.WriteLine(x1.GetValueOrDefault(int.MinValue) >= x2.GetValueOrDefault(int.MinValue));

(Of course, you can use this approach only if you're sure that operands can be assigned the int.MinValue value.) Besides being available in VB2005 as well, a minor advantage of these techniques is that they generate fewer IL code that is also slightly faster than the code produced by comparison operators. These operators, in fact, always invoke the GetValueOrDefault AND the HasValue property behind the scenes.

C#
 
Get RSS/Atom Feed
RSS 2.0 | Atom 1.0
Search in the blog
Archive
<July 2008>
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789
Categories

Powered by: newtelligence dasBlog 1.8.5223.1