Creating an Array in C#

An array is a data structure that contains several variables of the same type or group of same data type that share a same name.

Declaration of array

C# supports single-dimensional arrays, multidimensional arrays (rectangular arrays), and array-of-arrays (jagged arrays).
Array in C# are declared as follow:

Type[ ] arrayname;

The following examples show how to declare different kinds of arrays:

Single-dimensional arrays:

int[] numbers;

Multidimensional arrays:

string[,] names;

Array-of-arrays (jagged):

byte[][] scores;

remember, we do not enter the size of the arrays in the declaration.

Creation of Arrays

After declaring  an array, we need to create it in the memory, C# allows us to create arrays using new operator only, shown below:

arrayname = new type[size]

The following examples show how to create different kinds of arrays:

Single-dimensional arrays:

int[] numbers = new int[5];

Multidimensional arrays:

string[,] names = new string[5,4];

Array-of-arrays (jagged):

byte[][] scores = new byte[5][];

for (int i = 0; i < Arrjagged.Length; i++)
{
Arrjagged[i] = new byte[4];
}

Example

private void ExampleArray()
{
// Declare a single-dimensional array
int[] arr1 = new int[2];

// Declare and set array element values
int[] arr2 = new int[] { 1, 3, 4, 7, 9 };

// Declare a two dimensional array
int[,] multiDimensionalArr1 = new int[2, 3];

// Declare and set array element values
int[,] multiDimensionalArr2 = { { 1, 2}, { 4, 5 } };

// Declare a jagged array
int[][] jaggedArr1 = new int[6][];

// Set the values of the first array in the jagged array structure
jaggedArr1[0] = new int[4] { 1, 2, 3, 4 };
}