C # Get multidimensional array type

How can I get the type of the innermost elements of a multidimensional array?

var qq = new int[2,3]{{1,2,3}, {1,2,4}};
var t = qq.GetType().ToString();//is "System.Int32[,]"
var t2 = ??; // should be "System.Int32"

I would like to get the innermost element type regardless of the number of dimensions of the array (Rank).

+5
source share
2 answers

Use GetElementType():

var t2 = qq.GetType().GetElementType().ToString(); 
+13
source

When you find a lack of methods from what you need, you can always write your own extension methods.

public static Type GetEssenceType(this Type node) {
    for(Type head=node, next; ; node=next)
        if(null==(next=node.GetElementType()))
            return node!=head?node:null;
}

It returns the type of the innermost element (which I called the entity type ) if the given type (with a name nodein the code) was a type that has an element type; otherwise null.


Edit:

Type has an internal method that does the same:

internal virtual Type GetRootElementType()
{
    Type elementType = this;
    while (elementType.HasElementType)
    {
        elementType = elementType.GetElementType();
    }
    return elementType;
}

:

var bindingAttr=BindingFlags.Instance|BindingFlags.NonPublic;
var method=typeof(Type).GetMethod("GetRootElementType", bindingAttr);
var rootElementType=(Type)method.Invoke(givenType, null);

, GetRootElementType , .

+2

All Articles