Why is CType complaining (InvalidCastException
) about taking an object (that is really an Int32?
) and converting it to an Int64?
?
I've found that CTypeDynamic isn't having an issue (tangential though, as I'm focused on Ctype
).
Here is a code sample to reproduce the scenario.
Module Module1
Sub Main()
Dim i As Int32? = 1234567891
'manual nullable -> non nullable -> non nullable -> nullable
'per https://stackoverflow.com/a/10065482/392175
Dim iNotNullable As Int32 = i.Value
Dim biNotNullable As Int64 = iNotNullable
Dim bi As Int64? = biNotNullable
Console.WriteLine($"---Manual results---")
Console.WriteLine($"i={i}")
Console.WriteLine($"bi={bi}")
'CType investigation
bi = Module1.xCType(Of Int64?)(i)
Console.WriteLine($"---CType results---")
Console.WriteLine($"i={i}")
Console.WriteLine($"bi={bi}")
Console.ReadLine()
End Sub
Public Function [xCType](Of T)(ByVal obj As Object) As T
If obj Is Nothing Then Return Nothing
If IsDBNull(obj) Then Return Nothing
Return obj 'fails
Return CType(obj, T) 'fails
Return CTypeDynamic(Of T)(obj) 'succeeds
End Function
End Module