Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the type of the objects stored in a generic list?

Given a generic list of type List<T> how do I find type T?

I suppose if the list is populated I could take listInstance[0].GetType() but that seems a bit hackish.

Edit:

For context, I want to populate a DataTable with columns based on the Properties of an object. Where an object property is a generic list I want to add a column for each property of the object stored by the list. I'll flatten the data structure to fit into a DataRow later.

The reason I don't want to use the type of the first object in the list is because it's not guaranteed that every instance will have the list populated. Some will and some won't, but I'll still need all the columns ahead of time.

like image 698
Phil Gan Avatar asked Dec 29 '22 02:12

Phil Gan


1 Answers

You could try

typeof(List<T>).GetGenericArguments()[0]

This works with an empty array, while your version does not.

UPDATE:

On an instance use

instance.GetType().GetGenericArguments()[0]
like image 110
Michael Stoll Avatar answered Jan 11 '23 19:01

Michael Stoll