Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Type that describes an array of a base type?

I need to create a Type instance for an array of a base type with a specified number of indexes. Essentially I need to method like the following that I can call...

public Type GetArrayOfType(Type baseType, int numOfIndexes)
{
    return /* magic does here */
}

So that calling the function would give the following result...

GetTypeArray(typeof(bool), 1) == typeof(bool[])
GetTypeArray(typeof(bool), 2) == typeof(bool[,])
GetTypeArray(typeof(bool), 3) == typeof(bool[,,])

The only solution I can come up with is the following...

public Type GetArrayOfType(Type baseType, int numOfIndexes)
{
    List<int> indexes = new List<int>();
    for(int i=0; i<numOfIndexes; i++)
        indexes.Add(1);

    return Array.CreateInstance(baseType, indexes.ToArray()).GetType();
}

This does work but having to create an instance of the required type in order to then call GetType() does not seem ideal. There must be a way to generate the Type without creating an instance. Or is there?

like image 631
Phil Wright Avatar asked Dec 04 '12 02:12

Phil Wright


1 Answers

You can do it like this:

public Type GetArrayOfType(Type baseType, int numOfIndexes) {
    return numOfIndexes == 1 ? baseType.MakeArrayType() : baseType.MakeArrayType(numOfIndexes);
}

There is a little trick there: although you can pass 1 to MakeArrayType(int), the type that it is going to produce will not be the same as that returned by MakeArrayType. Here is an excerpt from the documentation:

The common language runtime makes a distinction between vectors (that is, one-dimensional arrays that are always zero-based) and multidimensional arrays. A vector, which always has only one dimension, is not the same as a multidimensional array that happens to have only one dimension. You cannot use this method overload to create a vector type; if rank is 1, this method overload returns a multidimensional array type that happens to have one dimension. Use the MakeArrayType() method overload to create vector types.

like image 70
Sergey Kalinichenko Avatar answered Sep 30 '22 13:09

Sergey Kalinichenko