C# Tutorials

Jagged Array:

A jagged array is an array of an array. Jagged arrays store arrays instead of any other data type value directly.

A jagged array is initialized with two square brackets [][]. The first bracket specifies the size of an array and the second bracket specifies the dimension of the array which is going to be stored as values. (Remember, jagged array always store an array.)

The following jagged array stores a two single dimensional array as a value:

Example: Jagged Array
            
int[][] intJaggedArray = new int[2][];

intJaggedArray[0] = new int[3]{1,2,3};

intJaggedArray[1] = new int[2]{4,5};

Console.WriteLine(intJaggedArray[0][0]); // 1

Console.WriteLine(intJaggedArray[0][2]); // 3
    
Console.WriteLine(intJaggedArray[1][1]); // 5

The following jagged array stores a multi-dimensional array as a value. Second bracket [,] indicates multi-dimension.

Example: Jagged Array
    
int[][,] intJaggedArray = new int[3][,];

intJaggedArray[0] = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
intJaggedArray[1] = new int[2, 2] { { 3, 4 }, { 5, 6 } }; 
intJaggedArray[2] = new int[2, 2];

Console.WriteLine(intJaggedArray[0][1,1]); // 4

Console.WriteLine(intJaggedArray[1][1,0]); // 5

Console.WriteLine(intJaggedArray[1][1,1]); // 6

Note : Be careful while working with jagged arrays. It will throw an IndexOutOfRange exception if the index does not exist.
;