C# Jagged Array

http‮‬s://www.theitroad.com

In C#, a jagged array is an array of arrays, where each element of the main array is an array itself. Unlike multidimensional arrays, jagged arrays can have different lengths for each of their sub-arrays.

A jagged array is declared using the following syntax:

type[][] arrayName = new type[size1][];

In this syntax, type is the data type of the array elements, arrayName is the name of the array, and size1 is the size of the main array. Each element of the main array is a reference to another array, which can have a different size.

Here's an example of how to declare and initialize a jagged array in C#:

int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] {1, 2, 3};
jaggedArray[1] = new int[] {4, 5};
jaggedArray[2] = new int[] {6, 7, 8, 9};

In this example, we declare a jagged array named jaggedArray with three elements, where each element is an integer array of different lengths. The first element has three elements, the second has two elements, and the third has four elements.

We can also initialize a jagged array using an array initializer:

int[][] jaggedArray = new int[][] {
    new int[] {1, 2, 3},
    new int[] {4, 5},
    new int[] {6, 7, 8, 9}
};

To access the elements of a jagged array, you need to specify the indices of the main array and the sub-array. For example, to access the element in the second sub-array and the first element of that sub-array in the jaggedArray, you would use the following code:

int element = jaggedArray[1][0]; // second sub-array, first element

In this code, jaggedArray[1][0] returns the value 4, which is the first element of the second sub-array in the jaggedArray.