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#
5/20/2008 5:54:54 PM (GMT Daylight Time, UTC+01:00)
Reference: Very helpful, thanks!!
7/21/2008 3:32:33 PM (GMT Daylight Time, UTC+01:00)
Nike,Jordan,Air force 1 sneaker - We supply brand shoes (air max, jordan,nike shox,adidas, af1, bape, dunk, iceream, puma, timberland, etc), bags, jeans,t-shirt.
website: www.sneakersupplier.com
1/1/2010 4:08:21 PM (GMT Standard Time, UTC+00:00)
good aritilcle
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

 
Get RSS/Atom Feed
RSS 2.0 | Atom 1.0
Search in the blog
Archive
<March 2010>
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910
Categories

Powered by: newtelligence dasBlog 1.8.5223.1