Language: EN

csharp-que-son-arrays

What are and how to use arrays in C#

An Array is a collection of variables of the same type, and of a fixed size. These are stored in contiguous memory locations.

Each element of the array can be accessed using a numeric index, starting from zero. For this, we use the operator [].

Arrays in C# are of type System.Array. This class provides us with the necessary methods and properties to work with arrays.

Array Declaration

The basic syntax for declaring an Array is:

Type[] arrayName;

Where,

  • Type, the data type it will contain

Note that it is not necessary to specify the number of elements in the Array, because we are only defining a variable that references an Array.

For example, to declare an array of integers:

int[] myNumbers;

In our variable myNumbers, we can now reference any Array.

Creating an Array

Once an Array is declared, before we can use it, we must initialize it. This will allocate memory to store its elements.

We can create an “empty” Array. In this case, all values in the array are initialized to the default value of the type.

For example, this would create an array with 5 int values initialized to 0, because 0 is the default value for the int type.

int[] numbers = new int[5]; // Array of 5 elements

Array Initialization

Alternatively, we can initialize the Array with a collection of given values. For example:

// recommended syntax
int[] numbers = [ 1, 2, 3, 4, 5 ];



// equivalent to this
int[] numbers = { 1, 2, 3, 4, 5 };
int[] numbers = new int[] { 1, 2, 3, 4, 5 };

Using the Array

Accessing Array Elements

Each element of an array is accessed using an index that starts from 0. The syntax to access an element is:

arrayName[index]

For example:

int[] numbers = { 1, 2, 3, 4, 5 };
int firstNumber = numbers[0]; // firstNumber will be 1

Modifying Array Elements

The elements of an array can be modified by assigning new values to specific indices:

int[] numbers = { 1, 2, 3, 4, 5 };
numbers[2] = 10; // The third element of the array will now be 10

Useful Array Methods and Properties

Lists in C# offer a wide range of operations that allow us to manipulate and access their elements efficiently. Let’s look at some of them:

Array Length

The Length property returns the total number of elements in an array:

int[] numbers = { 1, 2, 3, 4, 5 };
int length = numbers.Length; // length will be 5

Sorting an Array

The Sort method of the Array class allows sorting the elements of an array:

int[] numbers = { 5, 3, 1, 4, 2 };
Array.Sort(numbers); // numbers will now be { 1, 2, 3, 4, 5 }

Reversing an Array

The Reverse method reverses the order of elements in an array:

int[] numbers = { 1, 2, 3, 4, 5 };
Array.Reverse(numbers); // numbers will now be { 5, 4, 3, 2, 1 }

Practical Examples