Mega Code Archive

 
Categories / C# Book / 09 Reflection
 

0612 Obtaining array types

You can also obtain an array type by calling MakeArrayType on the element type: using System; using System.Reflection; using System.Collections.Generic; class MainClass { static void Main() { Type tSimpleArray = typeof(int).MakeArrayType(); Console.WriteLine(tSimpleArray == typeof(int[])); // True } } MakeArray can be passed an integer argument to make multidimensional rectangular arrays: using System; using System.Reflection; using System.Collections.Generic; class MainClass { static void Main() { Type tCube = typeof(int).MakeArrayType(3); // cube shaped Console.WriteLine(tCube == typeof(int[, ,])); // True } } GetElementType does the reverse; it retrieves an array type's element type: using System; using System.Reflection; using System.Collections.Generic; class MainClass { static void Main() { Type e = typeof(int[]).GetElementType(); //GetArrayRank returns the number of dimensions of a rectangular array: int rank = typeof(int[, ,]).GetArrayRank(); // 3 } }