views:

137

answers:

1

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
+1  A: 

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 inner DirectCast (T0 -> Object) is OK, because T0 is a subclass of Object.
  • The outer DirectCast (Object -> T1) is OK, because T1 is a subclass of Object (of course, such a cast might fail at run-time).

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))
Heinzi
Brilliant, thanks!
David Rutten