News & UpdatesProgrammingWeb programming StoreMy Projects

C# Tutorial – 07 – Arrays

An array is a data structure used for storing a collection of values that all have the same data type.

Array declaration

To declare an array, a set of square brackets is appended to the data type the array will contain, followed by the array’s name. An array can be declared with any data type and all of its elements will then be of that type.

int[] x; // not int x[]

Array allocation

The array is allocated with the new keyword, followed again by the data type and a set of square brackets containing the length of the array. This is the fixed number of elements that the array can contain. Once the array is created, the elements will automatically be assigned to the default value for that data type.

int[] x = new int[3];

Array assignment

To fill the array elements they can be referenced one at a time and then assigned values. An array element is referenced by placing the element’s index inside square brackets. Notice that the index for the first element starts with zero.

x[0] = 1;
x[1] = 2;
x[2] = 3;

Alternatively, the values can be assigned all at once by using a curly bracket notation. The new keyword and data type may optionally be left out if the array is declared at the same time.

int[] y = new int[] { 1, 2, 3 };
int[] z = { 1, 2, 3 };

Array access

Once the array elements are initialized, they can be accessed by referencing the elements’ indexes inside the square brackets.

System.Console.Write(x[0] + x[1] + x[2]); // "6"

Rectangular arrays

There are two kinds of multi-dimensional arrays in C#: rectangular and jagged. A rectangular array has the same length of all sub-arrays and separates the dimensions using a comma.

string[,] x = new string[2, 2];

As with single-dimensional arrays, they can either be filled in one at a time or all at once during the allocation.

x[0, 0] = "00"; x[0, 1] = "01";
x[1, 0] = "10"; x[1, 1] = "11";
string[,] y = { { "00", "01" }, { "10", "11" } };

Jagged arrays

Jagged arrays are arrays of arrays, and can have irregular dimensions. The dimensions are allocated one at a time and the sub-arrays can therefore be allocated to different sizes.

string[][] a = new string[2][];
a[0] = new string[1]; a[0][0] = "00"; 
a[1] = new string[2]; a[1][0] = "10"; a[1][1] = "11";

It is possible to assign the values during the allocation.

string[][] b = { new string[] { "00", "01" }, 
                 new string[] { "10", "11" } };

These are all examples of two-dimensional arrays. If more than two dimensions are needed, more commas can be added for the rectangular array, or more square brackets for the jagged array.