Get the actual type T in the general list <T>

How to get the actual type T in the general list at runtime using reflection?

+4
source share
4 answers

It depends on what you ask:

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

    Answer: typeof(T)

  • I have an object that contains a List<T> for some type T How to get type T through 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]; 
+8
source

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

For example, this will return 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"); } 
+2
source
 typeof (T) 

or

 typeof (T).UnderlyingSystemType 
+1
source

Old problem of a new solution on dynamic

 void Foo(){ Type type GetTypeT(data as dynamic); } private static Type GetTypeT<T>(IEnumerable<T> data) { return typeof(T); } 
0
source

All Articles