Jacob Mason Jacob Mason - 1 year ago 92
Vb.net Question

How to create a generic list of generics?

Please see my below code, I am trying to create a list of an interface which uses generics, but I need the generic version. So that you're aware, the generic type may differ for each entry in the list, it won't just be a list of IFoo with the same generic type.

Please let me know if you need clarification.

Public Interface IFoo

End Interface

Public Interface IFoo(Of T)
Inherits IFoo

Function Bar(foo As T) As T

End Interface

Public Class Foo(Of T)
Implements IFoo(Of T)

Private ReadOnly Foos As List(Of IFoo)

Public Function Bar(foo As T) As T Implements IFoo(Of T).Bar
For Each i In Foos
' Can't call Bar function from IFoo(Of T) as IFoo does not define the Bar function.
End Function
End Class

Answer Source

About generic types, there is something you need to understand is that an object of type IFoo(Of String) is a completely different type from IFoo(Of Integer), they have almost nothing in common actually.

If IFoo(Of T) inherits from IFoo, then the only thing they have in common is IFoo.

So if you try running a loop and call a method they all have in common, you must put that method inside IFoo.

Also, even if you could do it, how would you manage the parameter ?

 For Each i In Foos
      'Let's say you can call it from here
      Dim Myparam As ??? 'What type is your param then ?
      i.Bar(of <What do you put here ?>)(Myparam)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download