C# DBNull and nullable Types - cleanest form of conversion

user111013 picture user111013 · Nov 10, 2009 · Viewed 41.8k times · Source

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.

Answer

Ruben Bartelink picture Ruben Bartelink · Nov 10, 2009

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 = dr.Field<int?>( "Field" );

Or

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

Or

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