csharp / intermediate
Snippet
Initializing and Accessing Jagged Arrays
Jagged arrays are arrays of arrays where each row can have a different length. This is more memory-efficient than a multidimensional array (rectangular) when the data is sparse or uneven.
snippet.cs
csharp
1
2
3
4
5
6
int[][] matrix = new int[3][];matrix[0] = new int[] { 1, 2 };matrix[1] = new int[] { 3, 4, 5 };matrix[2] = new int[] { 6 };int value = matrix[1][2]; // Returns 5
Breakdown
1
int[][] matrix = new int[3][]
Declares an array that will hold three separate integer arrays.
2
matrix[1] = new int[] { 3, 4, 5 }
Initializes the second element of the main array with a 3-element integer array.