jae-l
6/2/2017 - 12:18 PM

Example of how to declare, allocate, and initialize one-dimensional, multidimensional, and jagged arrays.

Example of how to declare, allocate, and initialize one-dimensional, multidimensional, and jagged arrays.

//  Declare a normal one-dimensional array.
int[] array = new int[5] { 5, 4, 3, 2, 1 };

//  Declare a two-dimensional array.
int[,] array2d = new int[4, 2] { 
  { 1, 2 }, 
  { 3, 4 }, 
  { 5, 6 }, 
  { 7, 8 } 
};

//  Declare a three-dimensional array.
int[, ,] array3d = new int[2, 2, 3] { 
  { { 1, 2, 3 }, { 4, 5, 6 } },
  { { 7, 8, 9 }, { 10, 11, 12 } }
};

//  Declare a jagged array.
int[][] jaggedArray = {
  new int[] {15, 9, 7},
  new int[] {18, 25, 70},
  new int[] {2, 29}
};

//  Declare a two-dimensional jagged array.
int[][,] jaggedArray2d = new int[2][,];
jaggedArray2d[0] = new int[,] { { 4, 18 }, { 145, 343 } };
jaggedArray2d[1] = new int[,] { { 1, 55, 9 }, { 12, 6, 2 } };