I am currently fighting an old api and I am facing the following problem: I get runtime exceptions when I try to cast an Object to an array of Objects when the values are nullable dates.
Module Module1
Sub Main()
Console.WriteLine(Misc.dateCast(New Nullable(Of DateTime)()))
Console.WriteLine(Misc.tabledateCast(New Nullable(Of DateTime)() {New DateTime()}))
End Sub
End Module
Module Misc
Function dateCast(ByVal val As Nullable(Of DateTime)) As Object
Return CType(val, Object)
End Function
Function tabledateCast(ByVal val As Object) As Object()
Return CType(val, IEnumerable(Of Object)).Cast(Of Object).ToArray
End Function
End Module
The first cast is working, but not the second. How to cast successfully to an array of objects?
I cannot use CType(val, IEnumerable(Of Nullable(Of DateTime))) because the function may get arrays of other types.
Looks like you’ve got two choices:
1) If the arrays themselves are type-safe, you can genericize the method so that it knows what to cast to before casting to an object – not the nicest code to look at, especially in VB.NET:
2) Laoujin’s link, where you do a non-generic
IEnumerablecast first: