C# allows us to have arrays of arrays, which we call jagged arrays. An array of arrays is basically an array in which each row is actually another array on its own.
This is an example of declaration for an array of arrays:
1 2 3 4 5 |
int[][] arrayOfArrays; arrayOfArrays = new int[3][]; arrayOfArrays[0] = new int[3]; arrayOfArrays[1] = new int[7]; arrayOfArrays[2] = new int[4]; |
and this is how we initialize it:
1 2 3 4 5 6 |
int[][] arrayOfArrays = { new int[] {1, 7, 2}, new int[] {2, 3, 1}, new int[] {6, 45} }; |
Also, the arrays of the array can be one dimensional or multi-dimensional arrays, like we learned:
1 2 3 |
int[][,] arrayOfArrays = new int[2][,]; arrayOfArrays[0] = new int[,] { { 5, 15 }, { 125, 206 } }; arrayOfArrays[1] = new int[,] { { 3, 4, 5 }, { 7, 8, 9 } }; |
Finally, getting or setting the elements of an array of an array (lol, that sounds so complicated 😐 ):
1 |
arrayOfArrays[0][2] = 28; |
Most of the times, arrays of arrays won’t be of a real use to you, there are simpler ways of doing this. However, it is good to have a vague idea in a corner of your mind about them, just in case you ever encounter a situation that would really require this concept.
The concepts explained in this lesson are also shown visually as part of the following video:
Tags: arrays, arrays of arrays