Nullable types in strongly-typed datatables/datasets - workarounds?

Brady Moritz picture Brady Moritz · Jul 29, 2010 · Viewed 14.1k times · Source

Strongly-typed DataTables support "nullable" field types, except that the designer will not allow you change the setting to "allow nulls" for any value type fields. (ie: String types allow nullable, but int's do not).

The workaround is to call IsMyFieldNull() any time you want to get Myfield. If you access MyField when it does contain a null, it throws an eception.

This is a massive headache, in addition to causing many runtime bugs when a null showing up can cause your app to crash. I've complained to microsoft for years about this, yet every new release of visual studio still does not allow nullable value types to be used.

My question: Anyone know of a fancy extension method(s) that could be used to work around this major shortcoming?

Answer

M-Peror picture M-Peror · Dec 7, 2011

If you are using .Net 3.5 or higher, may be these extensions might be of use to you: http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.field.aspx

According to the documentation, it fully supports nullable types. It allows you to use constructs like

MyRow.Field<int?>("MyField") 

and if you assign it to or from an existing variable of the correct type, the compiler can infer the type automatically and you can leave out the type specifier, making it as short as

int? myVar = MyRow.Field("MyField");
MyRow.Field("MyField") = myVar;

Still not perfect, but a lot more legible than having to use IsMyFieldNull() etc everywhere.

Oh and if you want to be more on the safe side regarding misspelling column names, you can use things like

MyRow.Field(MyTable.MyFieldColumn)

Don't forget to add a reference to System.Data.DataSetExtensions.