newpost
newpost

Reputation: 83

Value of typeof(int[][]).GetArrayRank() is 1

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

typeof(int[][]).GetArrayRank();//1. 

Upvotes: 0

Views: 140

Answers (1)

CodeCaster
CodeCaster

Reputation: 151690

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);
    }
}

Upvotes: 5

Related Questions