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); // => TrueConsole.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); // => TrueConsole.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
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:
(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.
Remember Me
Powered by: newtelligence dasBlog 1.8.5223.1