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

Given a generic list of type List<T> , how to find type T ?

I assume that if the list is full, I could take listInstance[0].GetType() , but that seems a bit hacky.

Edit:

In context, I want to populate a DataTable with columns based on the properties of an object. If the property of the object is a general list, I want to add a column for each property of the object stored in the list. I will smooth the data structure to fit into the DataRow later.

The reason I don't want to use the type of the first object in the list is because it does not guarantee that each instance will have a populated list. Some will, and some won't, but I still need all the columns.

+4
source share
7 answers

You can try

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

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

UPDATE:

In case of use of an instance

 instance.GetType().GetGenericArguments()[0] 
+7
source

Why is this hacker? not hacks at all. Therefore, the GetType() method terminates. To get the type of object.

+1
source

These are hacks, because if the list is empty, you cannot get an answer.

You will need to reflect the Type type:

 List<int> mylist = new List<int>(); Type listType = mylist.GetType(); Type genericType = listType.GetGenericArguments()[0]; 
+1
source

you can use

  myList.GetType().GetGenericArguments() 

Returns an array of all types specified in the object declaration.

+1
source

Do it as you said. These are not hacks.

You can also call GetType () directly on your list and use it to look at its type T.

0
source

You can also do listInstance[0] is SomeTypeIExpectThisToBe if you expect a type and want to do something because of this

0
source

You must have access to the type parameter, so you can use typeof:

 void ProcessList<T>( List<T> listInstance) { Type type = typeof(T); } 
0
source

Source: https://habr.com/ru/post/1336308/


All Articles