In cases where my CLR object is Nullable, back when I was using VB.NET I used this extension method:
Private Function GetNullable(Of T As Structure)(ByVal row As System.Data.DataRow, ByVal fieldname As String, ByVal convert As Conversion(Of T)) As Nullable(Of T)
Dim nullable As Nullable(Of T)
If System.Convert.IsDBNull(row(fieldname)) Then
nullable = Nothing
Else
nullable = convert(row, fieldname)
End If
Return nullable
End Function
With the following delegate for Conversion(Of T)
:
Private Delegate Function Conversion(Of T)(ByVal row As System.Data.DataRow, ByVal fieldname As String) As T
I then layer on extensions for relevant datatypes:
<Extension()> _
Public Function GetDouble(ByVal row As System.Data.DataRow, ByVal name As String) As Double
Return Convert.ToDouble(row(name))
End Function
<Extension()> _
Public Function GetNullableDouble(ByVal row As System.Data.DataRow, ByVal name As String) As System.Nullable(Of Double)
Return GetNullable(Of Double)(row, name, AddressOf GetDouble)
End Function
Finally, I can use:
Dim amount As Double? = dr.GetNullableDouble("amount")