Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing result of "GetElementType" on arrays and generic lists

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)

like image 664
Rookian Avatar asked Feb 06 '11 13:02

Rookian


2 Answers

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();
like image 64
Ani Avatar answered Oct 14 '22 14:10

Ani


var elementType1 = typeof(List<A>).GetGenericArguments()[0]; 
var elementType = typeof(int[]).GetElementType();
like image 43
Snowbear Avatar answered Oct 14 '22 13:10

Snowbear