Phil Gan
Phil Gan

Reputation: 2863

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.

Upvotes: 4

Views: 321

Answers (7)

Dave
Dave

Reputation: 3621

It is hackish because if the list isn't populated, you can't get an answer.

You'll need to reflect against the Type:

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

Upvotes: 1

Tim Croydon
Tim Croydon

Reputation: 1896

You can use

 myList.GetType().GetGenericArguments()

This returns an array of all the types specified in the declaration of the object.

Upvotes: 1

Henrik
Henrik

Reputation: 23324

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

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

Upvotes: 0

TimC
TimC

Reputation: 1061

You could also do listInstance[0] is SomeTypeIExpectThisToBe if you are expecting a type and want to do something because of that

Upvotes: 0

Michael Stoll
Michael Stoll

Reputation: 1344

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]

Upvotes: 7

Liviu Mandras
Liviu Mandras

Reputation: 6607

Why is that hackish?, is not hackish at all. That is why the GetType() method exits. To obtain the type of the object.

Upvotes: 1

Al Kepp
Al Kepp

Reputation: 5980

Do it as you said. It is not hackish.

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

Upvotes: 0

Related Questions