Jagged arrays in C# are arrays of arrays, where each element is an array itself. They provide a flexible way to create multi-dimensional arrays with varying lengths for each dimension.
Unlike multidimensional arrays, jagged arrays allow each row to have a different number of columns. This flexibility makes them useful for scenarios where data structures have irregular shapes.
To declare a jagged array, use square brackets twice:
int[][] jaggedArray = new int[3][];
This creates an array with three elements, each of which is an array of integers. You can then initialize each inner array separately:
jaggedArray[0] = new int[4] { 1, 2, 3, 4 };
jaggedArray[1] = new int[3] { 5, 6, 7 };
jaggedArray[2] = new int[5] { 8, 9, 10, 11, 12 };
To access elements in a jagged array, use two sets of square brackets:
int element = jaggedArray[1][2]; // Accesses the third element (index 2) of the second array (index 1)
Use nested loops to iterate through all elements of a jagged array:
for (int i = 0; i < jaggedArray.Length; i++)
{
for (int j = 0; j < jaggedArray[i].Length; j++)
{
Console.Write(jaggedArray[i][j] + " ");
}
Console.WriteLine();
}
While both are used for storing multi-dimensional data, jagged arrays offer more flexibility. Choose jagged arrays when dealing with irregular data structures or when you need to dynamically resize inner arrays.
Jagged arrays are particularly useful in scenarios such as:
By mastering jagged arrays, you'll have a powerful tool for handling complex data structures in C#. They complement other array types and collection classes, providing flexibility and efficiency in your programming toolkit.