Jagged Arrays (C# Programming Guide)
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.
The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers:
Before you can use jaggedArray, its elements must be initialized. You can initialize the elements like this:
Each of the elements is a single-dimensional array of integers. The first element is an array of 5 integers, the second is an array of 4 integers, and the third is an array of 2 integers.
It is also possible to use initializers to fill the array elements with values, in which case you do not need the array size. For example:
You can also initialize the array upon declaration like this:
You can use the following shorthand form. Notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements:
A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.
You can access individual array elements like these examples:
It is possible to mix jagged and multidimensional arrays. The following is a declaration and initialization of a single-dimensional jagged array that contains three two-dimensional array elements of different sizes. For more information about two-dimensional arrays, see Multidimensional Arrays (C# Programming Guide).
You can access individual elements as shown in this example, which displays the value of the element [1,0] of the first array (value 5):
The method Length returns the number of arrays contained in the jagged array. For example, assuming you have declared the previous array, this line:
returns a value of 3.
This example builds an array whose elements are themselves arrays. Each one of the array elements has a different size.
class ArrayTest { static void Main() { // Declare the array of two elements: int[][] arr = new int[2][]; // Initialize the elements: arr[0] = new int[5] { 1, 3, 5, 7, 9 }; arr[1] = new int[4] { 2, 4, 6, 8 }; // Display the array elements: for (int i = 0; i < arr.Length; i++) { System.Console.Write("Element({0}): ", i); for (int j = 0; j < arr[i].Length; j++) { System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " "); } System.Console.WriteLine(); } // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } /* Output: Element(0): 1 3 5 7 9 Element(1): 2 4 6 8 */
- 8/25/2011
- Kaveh_Baghaee
- 4/19/2012
- Renegeddon