#127 – Declaring and Instantiating Jagged Arrays

It’s possible in C# to declare and instantiate jagged arrays. A jagged array is one that can have a different number of columns in each row (assuming the array is two-dimensional).  A jagged array can also be considered to be an array of arrays.

When you declare and instantiate a jagged array, you specify the size of only the first dimension.

// Jagged array - 3 elements, each of which is array of int
 int [][] nums2 = new int[3][];

After initialization, the jagged array consists of a one-dimensional array of arrays, with each element of the array initialized to null.

As a separate step, you can then initialize each element of the jagged array as a separate array, each of which can be a different size.

 nums2[0] = new int[4];
 nums2[1] = new int[2];
 nums2[2] = new int[10];
Advertisements