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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With