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?
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
is1
, this method overload returns a multidimensional array type that happens to have one dimension. Use theMakeArrayType()
method overload to create vector types.
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