How would I initialize a jagged array?

Hi,

I’m trying to create a jagged array to replace my 3D array. My code is below.

public Structure[][][] jaggedArray = new Structure; 

This error is being thrown,

“Invalid rank specifier: expected ‘,’ or ‘]’”

I assume my syntax is wrong, and that it’s thinking I’m trying to initialize a regular array. So my question would be, how would I initialize this array?

Okay, really sorry, I didn’t know what was a jagged array until now.

From this post : c# - Why we have both jagged array and multidimensional array? - Stack Overflow

You can initialize a jagged array like this :

MyClass[][] abc = new MyClass[10][];

for (int i=0; i<abc.Length; i++) 
    abc *= new MyClass[20];*

Your particular array would be initialized like this:

public Structure[][][] jaggedArray;
// [ ... ]
jaggedArray = new Structure[][];
for (int x = 0; x < Size; x++)
{
    var tmp1 = jaggedArray[x] = new Structure[];
    for (int y = 0; y < Size; y++)
    {
        var tmp2 = tmp1[y] = new Structure;
        for (int z = 0; z < Size; z++)
        {
            tmp2[z] = new Structure(); // or whatever you want to initialize each value.
        }
    }
}

The “tmp” variables are not necessary but they will speed up the process in case of a large “Size”. Without the tmp variables you would always need to index every array cascade each time you access the innermost element.

Without “tmp” it would look like this:

for (int x = 0; x < Size; x++)
{
    jaggedArray[x] = new Structure[];
    for (int y = 0; y < Size; y++)
    {
        jaggedArray[x][y] = new Structure;
        for (int z = 0; z < Size; z++)
        {
            jaggedArray[x][y][z] = new Structure(); // or whatever you want to initialize each value.
        }
    }
}