[quoted text, click to view] "Marc Gravell" <marc.gravell@gmail.com> wrote in message
news:24cfc7f1-39ac-4437-ae31-1d9bf8825019@8g2000hse.googlegroups.com...
> Why not obtain the ordinal of the column (GetOrdinal), then use
> IsDBNull to check for null on the column, then finally default(T)* to
> use the default value for that type. The only exception you might want
> here is string (since it looks like you want "") - although personally
> I'd find the null more correct, since you can differentiate between
> the null string and the empty string.
>
> (*=this is the C# syntax; I'm sure there is a VB equivalent, but I
> don't know what it is ;-p)
>
> Re casting the string (as an exception) - I don't know enough about
> VB, but in C# you can trick it by doing something like:
> return (T)(object)"";
Using a combination of your ideas I managed to come up with:
Public Shared Function CheckDbNull(Of T)(ByVal pReaderVar As Object)
As T
If pReaderVar.Equals(DBNull.Value) Then
Select Case GetType(T).ToString()
Case GetType(String).ToString()
Return CType(CType("", Object), T)
Case GetType(Nullable(Of DateTime)).ToString()
Return CType(CType(New Nullable(Of DateTime),
Object), T)
Case GetType(Nullable(Of Boolean)).ToString()
Return CType(CType(New Nullable(Of Boolean),
Object), T)
Case Else
Return Nothing
End Select
Else
Return CType(pReaderVar, T)
End If
End Function
Which seems to work great. Basically, I specify which types I want to add
explicit defaults for in the select case statement, and the case else
assigns nothing for the remaining types (which is the equivalent of
default() in C#), so for value types the default will be used (e.g.
integer=0).
Thanks for your help.