FWIW, I wrote a bunch of DataRow extension methods — CastAsXXX()
— to avoid having to deal with DB nullability...or at least defer it a bit B^). Here's my CastAsInt()
and CastAsIntNullable()
methods:
#region downcast to int
public static int CastAsInt( this DataRow row , int index )
{
return toInt( row[index] ) ;
}
public static int CastAsInt( this DataRow row , string columnName )
{
return toInt( row[columnName] ) ;
}
public static int? CastAsIntNullable( this DataRow row , int index )
{
return toIntNullable( row[index] );
}
public static int? CastAsIntNullable( this DataRow row , string columnName )
{
return toIntNullable( row[columnName] ) ;
}
#region conversion helpers
private static int toInt( object o )
{
int value = (int)o;
return value;
}
private static int? toIntNullable( object o )
{
bool hasValue = !( o is DBNull );
int? value = ( hasValue ? (int?) o : (int?) null ) ;
return value;
}
#endregion conversion helpers
#endregion downcast to int
Usage is pretty straightforward. You just need to state your expectations up front.
DataRow dr = GetADataRowFromSomewhere() ;
// Throws NullReferenceException if the column is null
int x = dr.CastAsInt( "column_1" ) ;
// Is perfectly happy with nulls (as it should be)
int? y = dr.CastAsIntNullable( "column_1" ) ;
I tried to make them generic, but no dice unless I'm willing to correlate NULLs from the database with the default value for the type (e.g., 0 for numeric types), which I'm not.