Confusing result of "GetElementType" on arrays and generic lists
Asked Answered
U

2

9

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)

Uropod answered 6/2, 2011 at 13:10 Comment(5)
Could you clarify what your remark "the generic list is boxed" means?Chromite
boxed means that you only have this list as an object.Uropod
That's not boxing. Boxing only applies to value-types.Chromite
@Chromite what is this then called?Uropod
List<T> is a reference-type; a value (in general : expression) of such a type is a reference to an object. I'm guessing you just have a variable of a less-specific type (e.g. object) that refers to a List<SomeT> instance. That's just about assignment-compatibility, not boxing. It's a representation-preserving conversion; no boxing happens.Chromite
C
14

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();
Chromite answered 6/2, 2011 at 13:12 Comment(2)
is there also a good approach to find out if I have a generic list or an array? I could proof for null and then use your solution, but maybe there is something better.Uropod
Array = type.IsArray. ListT = type.GetGenericTypeDefinition() == typeof(List<>) (You will also need to verify that the type is a constructed generic type).Chromite
C
5
var elementType1 = typeof(List<A>).GetGenericArguments()[0]; 
var elementType = typeof(int[]).GetElementType();
Consecutive answered 6/2, 2011 at 13:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.