Visual Studio 2005 & .NET 2.0 introduced a bunch of new concepts to .NET development, probably the most well known being Generics. One of the possibly less well know & certainly less well understood was the introduction of nullable types, specifically nullable value types. 

For the uninitiated, I’ve got a very brief intro below.  Here’s a more in-depth article on Nullables.

Value types (int, long, float, double, etc.) are not able to be set to a null value, they’re set to their default value (for numeric value types this is 0).  To make an int nullable, you append the type with a question mark, i.e. int? This means that you can now do this:

   1:  int? x;
   2:  //Some processing
   3:  if (x == null)
   4:  {
   5:      //Do something
   6:  }

Actually the nullable type wrapper gives you a more elegant way of checking for null with the HasValue property. All nullable types have this property & if the object is not null it will be true.  The nullable type specification is actually a bit of syntactic sugar: int? is just a compiler shortcut for the real Nullable type of Nullable<int>.

Right, nifty, but so what? How do we use this? Well a simple use is when you need to pass through an optional value to a SQL Server stored proc. Previously you’d have to write an overloaded version of the method that didn’t have the optional parameter and just create a null sql parameter for the command. With a nullable int, you can just pass the parameter through as null.

(more…)