Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 651
Cristian Diaconescu Avatar asked Jan 10 '12 15:01

Cristian Diaconescu


2 Answers

Use GetElementType():

var t2 = qq.GetType().GetElementType().ToString(); 
like image 150
D Stanley Avatar answered Sep 29 '22 20:09

D Stanley


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.

like image 45
Ken Kin Avatar answered Sep 29 '22 21:09

Ken Kin