Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DBNull and nullable Types - cleanest form of conversion

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" );

This is the purpose of the DataRowExtensions class in .NET 3.5, which provides static Field<T> and SetField<T> methods for round-tripping nullable (and non-nullable) data between the DataRow and .NET types.

int? fld = row.Field<int?>("ColumnA")

will set fld to null if row["ColumnA"] contains DBNull.Value, to its value if it contains an integer, and throw an exception if it contains anything else. And on the way back,

row.SetField("ColumnA", fld);

does the same thing in reverse: if fld contains null, it sets row["ColumnA"] to DBNull.Value, and otherwise sets it to the value of fld.

There are overloads of Field and SetField for all of the value types that DataRow supports (including non-nullable types), so you can use the same mechanism for getting and setting fields irrespective their data type.


int? a = (int?)dr["A"]

Why not use LINQ? It does the conversion for you.