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).
Use GetElementType()
:
var t2 = qq.GetType().GetElementType().ToString();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With