Will Hughes Will Hughes - 1 month ago 8
C# Question

C# DBNull and nullable Types - cleanest form of conversion

I have a DataTable, which has a number of columns. Some of those columns are nullable.

DataTable dt; // Value set.
DataRow dr; // Value set.

// dr["A"] is populated from T-SQL column defined as: int NULL


What, then, is the cleanest form of converting from a value in a DataRow, to a nullable variable.

Ideally, I would be able to do something like:

int? a = dr["A"] as int?;


Edit: Turns out you CAN do this, the side effect being that if your Schema types arn't ints, then this is ALWAYS going to return null. The answer by Ruben of using
dr.Field<int?>("A")
ensures type mismatches don't silently fail. This, of course, will be picked up by thorough unit tests.


Instead I'm usually typing something along the lines of:

int? a = (dr["A"] != DBNull.Value) ? (int)dr["A"] : 0;


This is a bunch more keystrokes, but more importantly there's more room for someone to stuff something up with a wrong keystroke.
Yes, a Unit Test will pick this up, but I'd rather stop it altogether.

What is the cleanest, least error prone pattern for this situation.

Answer

The LINQ to DataSets chapter of LINQ in Action is a good read.

One thing you'll see is the Field<T> extension method, which is used as follows:-

int? x = dt.Field<int?>( "Field" );

Or

int y = dt.Field<int?>( "Field" ) ?? 0;

Or

var z = dt.Field<int?>( "Field" );
Comments