csharp-que-son-arrays

What are and how to use arrays in C#

  • 6 min

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

Each element of the array can be accessed using a numerical 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.

If you want to learn more, check out the Introduction to Programming Course

Array Declaration

The basic syntax for declaring an Array is:

Type[] arrayName;
Copied!

Where,

  • Type, the type of data it will contain

For example, to declare an integer array:

int[] myNumbers;
Copied!

In our variable myNumbers we can now reference any Array.

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

Array Creation

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

For this, 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
Copied!

Array Initialization

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

// 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 };
Copied!

Using the Array

Accessing Array Elements

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

arrayName[index]
Copied!

For example:

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

Modifying Array Elements

Array elements 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
Copied!

Useful Array Methods and Properties

Arrays 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
Copied!

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 }
Copied!

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 }
Copied!

Practical Examples