Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 217
Mark Lauter Avatar asked Sep 15 '25 20:09

Mark Lauter


1 Answers

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)
like image 162
imoatama Avatar answered Sep 17 '25 18:09

imoatama