Reputation: 43
I have a generic wrapper class which can sometimes receive an array type as its generic. I can tell if the supplied generic type is an array by the IsArray property. But is there a way that I can obtain the type of the array elements in code? I've looked at all the exposed attributes of a Type object and just not seeing it.
Example:
public class wrap<T>
{
public void doSomething()
{
if (typeof(T).IsArray)
Type arrayElementType = typeof(T).??? ;
}
}
// typeof(T) when an array is "int[]"
// typeof(T).BaseType is "System.Array"
// how to get "int" out of this?
Upvotes: 4
Views: 144
Reputation: 113402
You're looking for the Type.GetElementType
method.
When overridden in a derived class, returns the Type of the object encompassed or referred to by the current array, pointer or reference type.
Type arrayElementType = typeof(T).GetElementType();
Upvotes: 4