Harry Stuart
Harry Stuart

Reputation: 1929

How do I create a rectangular array of arrays c#

I want to create a 2D array (essentially a grid) such that each element is an integer array of length 2 (each element represents a 2D vector).

I intuitively thought that this would work but I get invalid rank specifier:

int[][,] rarr = new int[2][100, 100];

Upvotes: 3

Views: 445

Answers (1)

Enigmativity
Enigmativity

Reputation: 117064

The code you're looking for is this:

int[][,] rarr = new int[2][,];
rarr[0] = new int[100, 100];
rarr[1] = new int[100, 100];

Or, more generally, this:

int[][,] rarr = new int[2][,];

for (int i = 0; i < 2; i++)
    rarr[i] = new int[100, 100];

Your code is attempting to allocate 3 distinct arrays in the one line of code - which you can't do. It's like you're trying to do the same as this illegal bit of code:

List<Dictionary<string, string>> x = new List<new Dictionary<string, string>()>();

I feel like, from your description, you really actually want this:

int[,][] rarr = new int[100,100][];

for (int i = 0; i < 100; i++)
    for (int j = 0; j < 100; j++)
        rarr[i, j] = new int[2];

Upvotes: 3

Related Questions