Jagged Array in C#

I was once asked a question in an interview, "What is jagged array?"

Let's find the solution to that question now.
 
Jagged array is just an array-of-arrays. It is defined as below: 
  1. string[][] sJaggedArray = new string[3][];  
  2.   
  3. sJaggedArray[0] = new string[]  
  4. {  
  5.     "One","Two","Three","Four"  
  6. };  
  7. sJaggedArray[1] = new string[]   
  8. {  
  9.     "One","Two","Three"  
  10. };  
  11. sJaggedArray[2] = new string[]   
  12. {  
  13.     "One","Two"  
  14. };  
  15.   
  16. for (int i = 0; i < sJaggedArray.Length; i++)   
  17. {  
  18.     for (int n = 0; n < sJaggedArray[i].Length; n++)   
  19.     {  
  20.         Console.WriteLine(sJaggedArray[i][n] + "\t");  
  21.     }  
  22.     Console.WriteLine();  
  23.   
  24. }  
In the example above, we have defined a multi-dimensional array and in each element of that array, we have described another one dimensional array.
 
The output of the above code would be as follows,
 
 
Now, one might argue that a jagged array is just a 2D array as that is also a combination of 1D arrays.
 
The reason that it is different is that each element of the jagged array can also be another 2D array. Please see more description below,
  1. string[][, ] sJaggedMultiDArray = new string[3][, ];  
  2.   
  3. sJaggedMultiDArray[0] = new string[, ]  
  4. {  
  5.     {  
  6.         "One","Two"  
  7.     },   
  8.     {  
  9.         "Three","Four"  
  10.     },  
  11.     {  
  12.         "Five","Six"  
  13.     }  
  14. };  
  15.   
  16. sJaggedMultiDArray[1] = new string[, ]   
  17. {  
  18.     {  
  19.         "One","Two"  
  20.     },   
  21.     {  
  22.         "Three","Four"  
  23.     }  
  24. };  
  25.   
  26. sJaggedMultiDArray[2] = new string[, ]   
  27. {  
  28.     {  
  29.         "One","Two"  
  30.     }  
  31. }; 
In the above code, we have defined a 2D array and in each of its elements, we have defined another 2D array of different sizes.
Up Next
Ebook Download
View all
Learn
View all