vb.netcastingdirectcast

DirectCast not accepting valid casts at compiletime (VB.NET)


How come this is not a valid DirectCast:

Public Sub FB(OF T0 As IGH_Goo, T1 As IGH_Goo) _
             (ByVal A As DataTree(Of T0), _
              ByVal B As DataTree(Of T1)) 

  Dim val_A As T1 = DirectCast(A.FirstItem, T1)  
End Sub

whereas this is:

Public Sub FB(OF T0 As IGH_Goo, T1 As IGH_Goo) _
             (ByVal A As DataTree(Of T0), _
              ByVal B As DataTree(Of T1)) 

  Dim val_A As T1 = DirectCast(DirectCast(A.FirstItem, Object), T1)  
End Sub

Solution

  • The compiler has no guarantee that T0 and T1 can be converted to each other. For example, T0 might be some class C0 (inheriting from IGH_Goo) and T1 might be some class C1 (also inheriting from IGH_Goo).

    The rule for DirectCast is: One of the classes must be a subclass of the other one. This is why your second example validates correctly:

    The DirectCast you are attempting (T0 -> T1) will never work, except for the special cases T0 = T1 or T0 inherits from T1.

    In the first case, your code should read

    Public Sub FB(Of T As IGH_Goo)
               (ByVal A As DataTree(Of T), ByVal B As DataTree(Of T)) 
    

    or, in the second case (also works for the first case):

    Public Sub FB(OF T0 As T1, T1 As IGH_Goo)
               (ByVal A As DataTree(Of T0), ByVal B As DataTree(Of T1))