I'm trying in VB.NET (framework 3.5) obtain the Type of a Nullable Property that has a Nothing value (its default value), to know how make the CType. The code would be something like this:
Class DinamicAsign
Public Property prop As Integer?
Public Property prop2 As Date?
Public Sub New()
Asign(prop, "1")
Asign(prop2, "28/05/2013")
End Sub
Public Sub Asign(ByRef container As Object, value As String)
If (TypeOf (container) Is Nullable(Of Integer)) Then
container = CType(value, Integer)
ElseIf (TypeOf (container) Is Nullable(Of Date)) Then
container = CType(value, Date)
End If
End Sub
End Class
This code doesn't work correctly. The problem is how to know the type of "container".
If "prop" has a value ("prop" is not nothing) this code works:
If (TypeOf(contenedor) is Integer) then...
If (contenedor.GetType() is Integer) then...
But if the value is nothing I have no idea how to obtain the Type. I've tried this ways, but don't work:
container.GetType()
TypeOf (contenedor) is Integer
TypeOf (contenedor) is Nullable(of Integer)
I know that someone could response that "container" is nothing because is not referencing any object and you can't know the Type. But this seems to be wrong because I have found a trick to solve this: creating a overloaded functions to make the cast, this way:
Class DinamicAsign2
Public Property prop As Integer?
Public Property prop2 As Date?
Public Sub New()
Asignar(prop, "1")
Asignar(prop2, "28/05/2013")
End Sub
Public Sub Asignar(ByRef container As Object, value As String)
AsignAux(container, value)
End Sub
Public Sub AsignAux(ByRef container As Integer, value As String)
container = CType(value, Integer)
End Sub
Public Sub AsignAux(ByRef container As Decimal, value As String)
container = CType(value, Decimal)
End Sub
End Class
If "container" Is Integer it will call to
public function AsignAux(byref container as Integer, value as string)
And if "container" Is Date will call to
public function AsignAux(byref container as Date, value as string)
This works right, .NET knows anyway the type of Object because calls to correct overloaded function. So I want to find out (as .NET does) a way to determine the Type of Nullable Object that has a nothing value.
Thx