In depth analysis of jagged arrays and implicitly typed arrays in C

  • 2021-09-05 00:42:08
  • OfStack

Interleaved array
A jagged array is an array whose elements are arrays. The dimensions and sizes of jagged array elements can vary. Interleaved arrays are sometimes called "arrays of arrays". The following example shows how to declare, initialize, and access a jagged array.
The following declares a 1-dimensional array of 3 elements, each of which is an array of 1-dimensional integers:


int[][] jaggedArray = new int[3][];

You must initialize the elements of jaggedArray before you can use it. You can initialize the element as shown in the following example:


jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];

Each element is a 1-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.
You can also use initializers to fill array elements with values, in which case the array size is not required. For example:


jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };

You can also initialize an array when you declare it, such as:


  int[][] jaggedArray2 = new int[][] 
{
  new int[] {1,3,5,7,9},
  new int[] {0,2,4,6},
  new int[] {11,22}
};

You can use the following shorthand format. Note that the new operator cannot be omitted from element initialization because there is no default initialization for the element:


  int[][] jaggedArray3 = 
{
  new int[] {1,3,5,7,9},
  new int[] {0,2,4,6},
  new int[] {11,22}
};

A jagged array is an array of arrays, so its elements are reference types and are initialized to null.
You can access individual array elements as shown in the following example:


// Assign 77 to the second element ([1]) of the first array ([0]):
jaggedArray3[0][1] = 77;

// Assign 88 to the second element ([1]) of the third array ([2]):
jaggedArray3[2][1] = 88;

You can mix jagged arrays with multidimensional arrays. The following declares and initializes a 1-dimensional jagged array that contains 3 2-dimensional array elements of different sizes. For more information about 2-dimensional arrays, see Multidimensional Arrays (C # Programming Guide).


int[][,] jaggedArray4 = new int[3][,] 
{
  new int[,] { {1,3}, {5,7} },
  new int[,] { {0,2}, {4,6}, {8,10} },
  new int[,] { {11,22}, {99,88}, {0,9} } 
};

Individual elements can be accessed as shown in this example, which displays the value of the element [1, 0] in the first array (the value is 5):

System.Console.Write("{0}", jaggedArray4[0][1, 0]);
The method Length returns the number of arrays contained in the jagged array. For example, assuming you have declared the first 1 arrays, this row:

System.Console.WriteLine(jaggedArray4.Length);
The return value is 3.
This example generates an array whose elements are the array itself. Every 1 array element 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


Implicitly typed arrays
You can create an implicitly typed array in which the type of the array instance is inferred from the element specified in the array initializer. The rules for any implicitly typed variable also apply to implicitly typed arrays.
In query expressions, implicitly typed arrays are commonly used with anonymous types, as well as object initializers and collection initializers 1.
The following example demonstrates how to create an array of implicit types:


class ImplicitlyTypedArraySample
{
  static void Main()
  {
    var a = new[] { 1, 10, 100, 1000 }; // int[]
    var b = new[] { "hello", null, "world" }; // string[]

    // single-dimension jagged array
    var c = new[]  
{ 
  new[]{1,2,3,4},
  new[]{5,6,7,8}
};

    // jagged array of strings
    var d = new[]  
{
  new[]{"Luca", "Mads", "Luke", "Dinesh"},
  new[]{"Karen", "Suma", "Frances"}
};
  }
}

Note that in the previous 1 example, square brackets were not used for implicitly typed arrays on the left side of the initialization statement. Also note that jagged arrays are initialized with new [] just like 1-dimensional arrays.
An array of implicit types in object initializers
When you create an anonymous type that contains an array, you must implicitly type the array in the object initializer for that type. In the following example, contacts is an array of implicitly typed anonymous types, where each anonymous type contains an array named PhoneNumbers. Note that the var keyword is not used internally in the object initializer.


jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
0



Related articles: