We currently have lots of checks in our businesslayer object's Load()
functions that look like:
If drCourse("txtTT MCnotes").Equal s(DBNull.Value) Then
Me._txtTTMCnote s = ""
Else
Me._txtTTMCnote s = CStr(drCourse(" txtTTMCnotes"))
End If
and
If drCourse("datTT MCarchived").Eq uals(DBNull.Val ue) Then
Me._datTTMCarch ived = New Nullable(Of DateTime)
Else
Me._datTTMCarch ived = CDate(drCourse( "datTTMCarchive d"))
End If
I'd like to tidy these up with a a static generic function that will check
for null, and then return either the value or a default value (e.g. int=0,
string="", nullables=new nullable) but am having problems with the return
type. I started with this:
Public Shared Function CheckDbNull(Of T)(ByVal pReaderVar As Object) As T
If pReaderVar.Equa ls(DBNull.Value ) Then
Return Nothing
Else
Return CType(pReaderVa r, T)
End If
End Function
Which works, but returns nothing, which is causing null reference
exceptions. I tried writing it like:
If pReaderVar.Equa ls(DBNull.Value ) Then
Select Case GetType(T).Full Name
Case "System.Str ing"
Return ""
Case "System.Int 32"
Return 0
' etc
End Select
But this doesn't compile, as the return type is not T. Also trying to use
e.g. Return CType("", T) doesn't work.
Does anyone know how to return a specific type based on the return type, or
do I have to create a separate function for each type I'm checking for?
functions that look like:
If drCourse("txtTT MCnotes").Equal s(DBNull.Value) Then
Me._txtTTMCnote s = ""
Else
Me._txtTTMCnote s = CStr(drCourse(" txtTTMCnotes"))
End If
and
If drCourse("datTT MCarchived").Eq uals(DBNull.Val ue) Then
Me._datTTMCarch ived = New Nullable(Of DateTime)
Else
Me._datTTMCarch ived = CDate(drCourse( "datTTMCarchive d"))
End If
I'd like to tidy these up with a a static generic function that will check
for null, and then return either the value or a default value (e.g. int=0,
string="", nullables=new nullable) but am having problems with the return
type. I started with this:
Public Shared Function CheckDbNull(Of T)(ByVal pReaderVar As Object) As T
If pReaderVar.Equa ls(DBNull.Value ) Then
Return Nothing
Else
Return CType(pReaderVa r, T)
End If
End Function
Which works, but returns nothing, which is causing null reference
exceptions. I tried writing it like:
If pReaderVar.Equa ls(DBNull.Value ) Then
Select Case GetType(T).Full Name
Case "System.Str ing"
Return ""
Case "System.Int 32"
Return 0
' etc
End Select
But this doesn't compile, as the return type is not T. Also trying to use
e.g. Return CType("", T) doesn't work.
Does anyone know how to return a specific type based on the return type, or
do I have to create a separate function for each type I'm checking for?
Comment