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 numerical index, starting from zero. To do this we use the operator [].

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

Declaration of arrays

The basic syntax for declaring an Array is:

Type[] arrayName;

Being,

  • Type, data type it will contain

Notice that it is not necessary to indicate the number of elements of 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 assign memory to store its elements.

For this we can create an “empty” Array. In this case, all the values of 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

Initialization of arrays

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 };

Using the array

Access to elements of an array

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

arrayName[index]

For example:

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

Modifying elements of an array

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 see some of them:

Length of the array

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

Sort an array

The Sort method of the Array class allows you to sort the elements of an array:

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

Reverse an array

The Reverse method reverses the order of the 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

Calculating the average of an array of integers

This example shows how to calculate the average of the elements in an array of integers.

int[] numbers = { 1, 2, 3, 4, 5 }; // We declare the array with the numbers
int sum = 0; // Variable to store the sum of the elements

for (int i = 0; i < numbers.Length; i++)
{
    sum += numbers[i]; // Sum each element of the array to 'sum'
}

double average = (double)sum / numbers.Length; // Calculates the average
Console.WriteLine($"The average is: {average}");

Find the maximum value in an array

This example shows how to find the maximum value in an array of integers.

int[] numbers = { 1, 2, 3, 4, 5 }; // We declare the array with the numbers
int max = numbers[0]; // Initializes 'max' with the first element of the array

for (int i = 1; i < numbers.Length; i++)
{
    if (numbers[i] > max) // Compares each element with 'max'
    {
        max = numbers[i]; // Update 'max' if a greater value is found
    }
}

Console.WriteLine($"The maximum value is: {max}");

Count how many elements are greater than a given value

This example counts how many elements in an array are greater than a specific value.

int[] numbers = { 1, 2, 3, 4, 5 }; // We declare the array with the numbers
int value = 3; // Reference value
int count = 0; // Variable to count the elements

for (int i = 0; i < numbers.Length; i++)
{
    if (numbers[i] > value) // Checks if the element is greater than 'value'
    {
        count++; // Increases the count if the condition is true
    }
}

Console.WriteLine($"There are {count} elements greater than {value}");

Find the position of an element in an array

This example shows how to find the position of a specific element in an array.

int[] numbers = { 1, 2, 3, 4, 5 }; // We declare the array with the numbers
int search = 4; // Element to search
int position = -1; // Initializes the position at -1 (value that indicates not found)

for (int i = 0; i < numbers.Length; i++)
{
    if (numbers[i] == search) // Compares each element with 'search'
    {
        position = i; // Update 'position' with the index of the found element
        break; // Exits the loop
    }
}

if (position != -1)
{
    Console.WriteLine($"The number {search} is in position {position}");
}
else
{
    Console.WriteLine($"The number {search} is not in the array");
}