Search code examples
vb.netilistgettype

VB.Net - how can i get the type of the object contained in an List


If I have a list...

dim l as List(of MyClass) = new List(of MyClass)

and I want to get the type of the objects contained in the list, how do I do that?

The obvious answer, that doesn't seem to be possible from my actual implementation, would be to do something like this...

public function GetType(byval AList as IList(of GenericType)) as System.Type
  dim lResult as system.type = nothing
  if AList.Count > 0 then lResult = AList(0).GetType
  return lResult
end function

But what if the list is empty and I still want to know the type it contains?


Solution

  • There's a good article on this at MSDN, here

    Basically you can use GetGenericArguments() to get an array of the types provided as arguments to your generic type. In the case of a List, there's only one argument so you will get what you need using eg

    dim l as List(of MyClass) = new List(of MyClass)
    dim t as Type = (l.GetGenericArguments())(0)