John Egbert
John Egbert

Reputation: 5756

Get actual type of T in a generic List<T>

How do I get the actual type of T in a generic List at run time using reflection?

Upvotes: 5

Views: 3297

Answers (4)

Thomas Andreè Wang
Thomas Andreè Wang

Reputation: 3429

New solution old problem by dynamic

void Foo(){
   Type type GetTypeT(data as dynamic);
}

private static Type GetTypeT<T>(IEnumerable<T> data)
{
    return typeof(T);
}

Upvotes: 0

Timwi
Timwi

Reputation: 66573

It depends on what exactly you’re asking:

  • While writing code inside a generic type Blah<T>, how do I get the reflection type T?

    Answer: typeof(T)

  • I have an object which contains a List<T> for some type T. How do I retrieve the type T via reflection?

    Short answer: myList.GetType().GetGenericArguments()[0]

    Long answer:

    var objectType = myList.GetType();
    if (!objectType.IsGenericType() ||
        objectType.GetGenericTypeDefinition() != typeof(List<>))
    {
        throw new InvalidOperationException(
            "Object is not of type List<T> for any T");
    }
    var elementType = objectType.GetGenericArguments()[0];
    

Upvotes: 9

Reed Copsey
Reed Copsey

Reputation: 564323

You can use Type.GetGenericArguments to return the type T in a List<T>.

For example, this will return the Type for any List<T> passed as an argument:

Type GetListType(object list)
{
    Type type = list.GetType();
    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
        return type.GetGenericArguments()[0];
    else
        throw new ArgumentException("list is not a List<T>", "list");
}

Upvotes: 2

Ivan Ferić
Ivan Ferić

Reputation: 4763

typeof (T)

or

typeof (T).UnderlyingSystemType

Upvotes: 1

Related Questions