views:

29

answers:

2

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?

A: 

Here is a similar question in C#:

http://stackoverflow.com/questions/557340/c-generic-list-t-how-to-get-the-type-of-t

kbrimington
Thanks, I had a look at this and it was very helpful, even in VB.net. I'm just now getting a chance to post my thanks because of the project deadline.
Mark Lauter
+1  A: 

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)
imoatama
Thank you for the swift resopnse. I've been wrapped up in this project - typical overly optimistic scheduling set by my client. I was able to use your example in some LINQ. The link the the MSDN article provided even more ideas. It's turned out great. Thanks again for the help!
Mark Lauter
Thanks for the feedback, it put a smile on my face :) If you've found my answer helpful, you can set it as the accepted answer by clicking the big tick to the left of it.
imoatama