Jagged arrays are arrays that instead of primitive types, contain arrays (or other collections). It's like an array of arrays - each array element contains another array.
They are similar to multidimensional arrays, but have a slight difference - as multidimensional arrays are limited to a fixed number of rows and columns, with jagged arrays, every row can have a different number of columns.
Declaring a jagged array
For example, declaring a jagged array with 8 columns:
int[][] a = new int[8][];
The second []
is initialized without a number. To initialize the sub arrays, you would need to do that separately:
for (int i = 0; i < a.length; i++)
{
a[i] = new int[10];
}
Getting/Setting values
Now, getting one of the subarrays is easy. Let's print all the numbers of the 3rd column of a
:
for (int i = 0; i < a[2].length; i++)
{
Console.WriteLine(a[2][i]);
}
Getting a specific value:
a[<row_number>][<column_number>]
Setting a specific value:
a[<row_number>][<column_number>] = <value>
Remember: It's always recommended to use jagged arrays (arrays of arrays) rather than multidimensional arrays (matrixes). It's faster and safer to use.
Note on the order of the brackets
Consider a three-dimensional array of five-dimensional arrays of one-dimensional arrays of int
. This is written in C# as:
int[,,][,,,,][] arr = new int[8, 10, 12][,,,,][];
In the CLR type system, the convention for the ordering of the brackets is reversed, so with the above arr
instance we have:
arr.GetType().ToString() == "System.Int32[][,,,,][,,]"
and likewise:
typeof(int[,,][,,,,][]).ToString() == "System.Int32[][,,,,][,,]"