DataSets and nullable types

Let's say you want to have a DataSet with an Integer column, and this column can have no values, which for argument's sake we'll call NULL values (there is a whole argument about NULL really means, but we'll punt on that). The DataSet has been around since the first version of the .NET Framework, and this problem has always existed, as has it's solution, DBNull. This works ok, but leads to a bunch of ugly code like the following.

int value = -1; // or some const value that represents null

if (dataRow.IsNull("myIntColumn") == false)

{

    value = (int)dataRow["myIntColumn"];

}

Fast forward to the current day. We've had nullable types for a couple of years now, so you can now write the following code.

int? value = null;

if (dataRow.IsNull("myIntColumn") == false)

{

    value = (int?)dataRow["myIntColumn"];

}

While we have nullable Integers, we’re still left with a bunch of ugly code that we shouldn’t need to write. However, if you are using Visual Studio 2008, you do have a new option, the Field<T> method that lives in the new System.Data.DataSetExtensions assembly. With this method, you can specify the type, and for nullable types, we handle the null conversions for you.

int? value = dataRow.Field<int?>("myIntColumn");

Does that mean we’re done, and we don’t need true nullable columns? I don’t think so, but we just finished Visual Studio 2008, so please stay tuned, and if this is an important feature to you, please let me know.