This is a mirror of official site: http://jasper-net.blogspot.com/

C#/.NET Little Wonders: The Nullable static class

| Sunday, July 3, 2011
Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain.

The index of all my past little wonders posts can be found here.

Today we’re going to look at an interesting Little Wonder that can be used to mitigate what could be considered a Little Pitfall.  The Little Wonder we’ll be examining is the System.Nullable static class.

No, not the System.Nullable<T> class, but a static helper class that has one useful method in particular that we will examine… but first, let’s look at the Little Pitfall that makes this wonder useful.

But first, let’s set the stage with an example comparing null values to non-null values…
Little Pitfall: Comparing nullable value types using <, >, <=, >=

Examine this piece of code, without examining it too deeply, what’s your gut reaction as to the result? 

int? x = null;
if (x < 100)
{

Console.WriteLine("True, {0} is less than 100.",
x.HasValue ? x.ToString() : "null");
}
else
{
Console.WriteLine("False, {0} is NOT less than 100.",
x.HasValue ? x.ToString() : "null");
}

Your gut might be to say either true or a NullReferenceException right?  It would seem to make sense that either you’d throw because one of the values was null, or that a null integer is less than the integer constant 100.  But the result is actually false!  The null value is not less than 100 according to the less-than operator.

It looks even more confusing when you consider this also evaluates to false:

int? x = null;
if (x < int.MaxValue)
{

// ...
}


Read more: James Michael Hare
QR: c.net-little-wonders-the-nullable-static-class.aspx

Posted via email from Jasper-net

0 comments: