Cristian Diaconescu
Cristian Diaconescu

Reputation: 35641

C# Get the type of a multidimensional array

How can I get the type of the inner-most 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'd like to get the innermost element type regardless of the number of dimensions of the array (Rank).

Upvotes: 5

Views: 1303

Answers (2)

Ken Kin
Ken Kin

Reputation: 4693

When you found there's a lack of methods out of the box of 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 inner-most element type(which I called the essence type) if the given type(named node in the code) was a type which has element type; otherwise, null.


Edit:

Type has a internal method does the similar thing:

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

You can create a delegate or use it via reflection:

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

Note that GetRootElementType returns the given type itself if it doesn't have element type.

Upvotes: 2

D Stanley
D Stanley

Reputation: 152556

Use GetElementType():

var t2 = qq.GetType().GetElementType().ToString(); 

Upvotes: 14

Related Questions