I have a function which for a given object loops through its properties (of several datatypes), but when I added one with the type SqlDateTime? I get an invalid cast exception. Here is the part
Dim cad As SqlString? = prop.GetValue(obj)
It fails because in the past the only nullable type was SqlString?, so I would like to know with which specific type of nullable(SqlString?, SqlDateTime?, etc.) I am dealing with.
Complete code
Class staticx
Public Property name As SqlString
Public Property address As sqlString?
Public Property dateAdded As SqlDateTime?
Public Shared Sub check(obj As staticx)
For Each prop As System.Reflection.PropertyInfo In GetType(staticx).GetProperties
If Nullable.GetUnderlyingType(prop.PropertyType) <> Nothing Then
Dim cad As SqlString? = prop.GetValue(obj)
End If
End Sub
End Class
Calling it
Dim wayne As New staticx With {.name= "jhon", .address= "ape", .dateAdded= Date.Today}
staticx.check(wayne)
To test for a specific type (e.g. SqlString? or SqlDateTime?) you could use the TypeOf operator, e.g:
If Nullable.GetUnderlyingType(prop.PropertyType) <> Nothing Then
If TypeOf prop.GetValue(obj) Is SqlString? Then
' Dim cad As SqlString? ...
ElseIf TypeOf prop.GetValue(obj) Is SqlDateTime? Then
' Dim cad As SqlDateTime? ...
Else
' Found another kind of Nullable type!
End If
...
Obviously this approach doesn't scale well in the face of new kinds of nullable types, but if you're comfortable that there aren't going to be a whole lot of other nullable types (or if you're only interested in handling these specific 2 nullable types), then this might be a workable approach.