DEV Community

jzfrank
jzfrank

Posted on

C# How to Initialize an Array: 1-d, n-d, and Jagged

One of the most widely used data type in C# is array. Array could be of 3 kinds: single-dimensional, multiple-dimensional, and jagged. What are they and how do we initialise them? This blog gives a concise introduction.

Single-dimensional array

default init

int[] arr_num = new int[10]; 
// by default, numerical values are filled with 0

string[] arr_str = new string[10];
// by default, reference type values are filled with null
// be careful, here, it is NOT empty string but NULL
Enter fullscreen mode Exit fullscreen mode

literal init

int[] arr_num = new int[] {1, 2, 3}; 
// or
int[] arr_num1 = {1,2,3}; // the compiler could infer type
// or
int[] arr_num2 = new int[3] {1, 2, 3}; // but why would anyone want such verbose declaration? 
Enter fullscreen mode Exit fullscreen mode

Multiple-dimensional array

default init

// 2-d array
int[,] arr_num = new int[10,2]; 
// by default, numerical values are filled with 0

string[,] arr_str = new string[10,2];
// by default, reference type values are filled with null
// be careful, here, it is NOT empty string but NULL

// 3-d array
int[,,] arr_num_3d = new int[3,3,4];

// the logic for declaring a n-d array is similar
Enter fullscreen mode Exit fullscreen mode

literal init

// 2x2 2-d array
int[,] arr_num = new int[,] {{1,2}, {3,4}}; 
// or
int[,] arr_num1 = {{1,2}, {3,4}}; // the compiler could infer type
// or
int[,] arr_num2 = new int[2,2] {{1,2}, {3,4}}; ; // but why would anyone want such verbose declaration? 
Enter fullscreen mode Exit fullscreen mode

Jagged array

A jagged array is an array whose elements are array. However, its element could be of different size.

default init

// 
int[][] jagged_arr = new int[2][]; 
// by default, numerical values are filled with 0

jagged_arr[0] = new int[2];
jagged_arr[1] = new int[3]; // could also literal init
// could of different size
Enter fullscreen mode Exit fullscreen mode

literal init

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

// jagged array whose elements are multiple-dim arrays
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} }
};
Enter fullscreen mode Exit fullscreen mode

Final remark

  • about default value behaviour: for numerical value types (int, decimal, double), filled with 0; for reference value types (string, array), filled with null
  • To create an m x n jagged array, the following code may deem useful:
int m=4, n=8;
int[][] dp = new int[m][];
for (int i=0; i<m; i++) dp[i] = new int[n];
Enter fullscreen mode Exit fullscreen mode

Top comments (0)