Generic TypeOf operator?
-
25-09-2019 - |
Question
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 ))
OTHER TIPS
Unfortunately, this is not possible.
You need to call GetType()
and check IsGenericType
and GetGenericTypeDefinition
.
See Hanselman's blog: http://www.hanselman.com/blog/TheVBEquivalentToCTypeofKeyword.aspx
GetType(T) - it is that simple :).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow