Jagged arrays
suggest changeJagged 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 rows. Each row is a separate array and is not created yet:
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 row of a (index 2):
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: A jagged array can give each row its own length. Indexing it is often faster than indexing a rectangular array. A rectangular array is one block, and none of its rows can be null.
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[][,,,,][,,]"