Generic list:
var elementType1 = typeof (List<A>).GetElementType();
Array:
var elementType = typeof (A[]).GetElementType();
Why do I only get the element type of an array? How could I get the element type of a generic list? (remark: the generic list is boxed)
GetElementType
only gets the element-type for array, pointer and reference types.
When overridden in a derived class, returns the Type of the object encompassed or referred to by the current array, pointer or reference type
The reflection API doesn't "know" that List<T>
is a generic container and that the type-argument of one of its constructed types is representative of the type of the elements it contains.
Use the GetGenericArguments
method instead to get the type-arguments of the constructed type:
var elementType1 = typeof(List<A>).GetGenericArguments().Single();
var elementType1 = typeof(List<A>).GetGenericArguments()[0];
var elementType = typeof(int[]).GetElementType();
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