A jagged array in C# is a multi-dimensional array comprising arrays of varying sizes as its elements. It’s also referred to as “an array of arrays” or “ragged array”.
In this quick tutorial, we’ll look more in-depth into defining and working with jagged arrays.
Creating Jagged Array
Using the Shorthand-Form
An easy way to define a jagged array would be:
1 2 3 |
int[][] jaggedArr = {{1, 2}, {3, 4, 5}, {6, 7, 8, 9}}; |
Here, we’ve declared and initialized jaggedArr in a single step
Declaration and then Initialization
1 2 3 |
int[][] jagArr = new int[3][]; |
The length of the first dimension is 3.The declaration can be read as “jagArr is an array of three arrays of ints.”
A jagged array can be of any number of dimensions greater than one.In rectangular arrays, dimension lengths cannot be included in the array type section of the declaration.
Syntax for jagged arrays requires a separate set of square brackets for each dimension. The number of sets of square brackets in the declaration of the array variable determines the rank of the array.
Here, we’ve omitted to specify the second dimension since it will vary.
Next, let’s go further by both declaring and initializing the respective elements within jaggedArr:
1 2 3 4 5 |
jaggedArr[0] = new int[] {1, 2}; jaggedArr[1] = new int[] {3, 4, 5}; jaggedArr[2] = new int[] {6, 7, 8, 9}; |
Memory Representation
How will the memory representation of our jaggedArr look like?
As we know, an array in C# is nothing but an object, the elements of which could be either primitives or references. So, a two-dimensional array in C# can be thought of as an array of one-dimensional arrays.
Our jaggedArr in memory would look similar to:
Clearly, jaggedArr[0] is holding a reference to a single-dimensional array of size 2,jaggedArr[1] holds a reference to another one-dimensional array of size 3 and so on.
This way C# makes it possible for us to define and use jagged arrays.
Iterating and Printing Elements Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Program { static void Main() { int[][,] JaggedArr; // An array of 2D arrays JaggedArr = new int[3][,]; // Instantiate an array of three 2D arrays. JaggedArr[0] = new int[,] { { 10, 20 }, { 100, 200 } }; JaggedArr[1] = new int[,] { { 30, 40, 50 }, { 300, 400, 500 } }; JaggedArr[2] = new int[,] { { 60, 70, 80, 90 }, { 600, 700, 800, 900 } };//Get length of dimension 0 of Arr. for (int i = 0; i < JaggedArr.GetLength(0); i++) {//Get length of dimension 0 of Arr[ i ]. for (int j = 0; j < JaggedArr[i].GetLength(0); j++) {//Get length of dimension 1 of Arr[ i ]. for (int k = 0; k < JaggedArr[i].GetLength(1); k++) { Console.WriteLine ("[{0}][{1},{2}] = {3}", i, j, k, JaggedArr[i][j, k]); } Console.WriteLine(""); } Console.WriteLine(""); } Console.ReadLine(); } } |
Output: