Search code examples
vb.nettypeofgenericsgeneric-type-argument

Generic TypeOf operator?


Dim x = GetType(List(Of )) 'valid statement
Dim list As New List(Of String)

Now I want to see if list is a List(Of T) variable:

Dim isList = TypeOf list Is List(Of )

On the last line I get a compile error: "Type Expected".

Is there any cheap-performance TypeOf operator alternative for generics?


Solution

  • You will have to do this with reflection:

    Dim type = list.[GetType]()
    Dim isList = type.IsGenericType AndAlso
        type.GetGenericTypeDefinition() = GetType(List(Of ))