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. To do 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.

Declaration of arrays

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 indicate 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.

Creation of arrays

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

To do this, we can create an “empty” Array. In this case, all 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 };

Use of the array

Accessing 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 efficiently manipulate and access their elements. 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 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]; // Adds each element of the array to 'sum'
}

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

Finding 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 maximum = numbers[0]; // Initializes 'maximum' with the first element of the array

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

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

Counting 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 counter = 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'
    {
        counter++; // Increments the counter if the condition is true
    }
}

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

Finding 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 for
int position = -1; // Initializes the position to -1 (value indicating not found)

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

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