0

Why is the value of typeof(int[][]).GetArrayRank() = 1, and how to create to Jagged array by reflection?

typeof(int[][]).GetArrayRank();//1. 
Aderbal Farias
  • 989
  • 10
  • 24
newpost
  • 73
  • 1
  • 7
  • [Same question](https://social.msdn.microsoft.com/Forums/vstudio/en-US/a07e6138-ccf2-4015-846c-df0cf2fedb27/creating-jagged-arrays-through-reflection?forum=netfxbcl) but not at SO. – Sinatr Apr 08 '19 at 07:19
  • 1
    Because jagged array is one-dimensional array. – Dmytro Mukalov Apr 08 '19 at 07:24

1 Answers1

5

A jagged array (int[][]) is different from a multidimensional array (int[,]):

var jagged = typeof(int[][]);
var multiDimensional = typeof(int[,]);

Console.WriteLine("Jagged: " + jagged.GetArrayRank()); // 1
Console.WriteLine("Multidimensional: " + multiDimensional.GetArrayRank()); // 2

To create a jagged array using reflection, you have to cobble it together from these resources:

First get the type information:

var typeOfInt = typeof(int);
var typeOfIntArray = typeOfInt.MakeArrayType();
var typeOfArrayOfIntArrays = typeOfIntArray.MakeArrayType();

Console.WriteLine(typeOfArrayOfIntArrays); // System.Int32[][]

Then instantiate and populate it:

// The root array has one element
var arrayOfIntArrays = (Array)Activator.CreateInstance(typeOfArrayOfIntArrays, 1);
// The inner array has two elements
var intArray = (Array)Activator.CreateInstance(typeOfIntArray, 2);

intArray.SetValue(42, 0);
intArray.SetValue(21, 1);

arrayOfIntArrays.SetValue(intArray, 0);

foreach (Array arr in arrayOfIntArrays)
{
    foreach (var value in arr)
    {
        Console.WriteLine(value);
    }
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Do you mean "*to create a multidimensional array using reflection...*"? – canton7 Apr 08 '19 at 07:27
  • @canton I've updated the answer. The answers I link to don't deal with jagged arrays. – CodeCaster Apr 08 '19 at 07:31
  • @canton7 typeof(int).MakeArrayType(dimension) – newpost Apr 08 '19 at 14:06
  • @yijiemanong Why the mention? My point was that he said "*To create a jagged array using reflection*" and then linked to a page which describes how to create a multidimensional array using reflection. He's since updated his answer with sample code to create a jagged array, so all is good. – canton7 Apr 08 '19 at 14:13