csharp-bucle-foreach

What is and how to use the FOREACH loop in C#

  • 6 min

The foreach loop is a control structure in C# that facilitates iteration over elements of a collection or data sequence (such as arrays, lists, or sets).

Unlike for, while, and do-while loops, the foreach loop is specifically used to iterate over each element of a collection without the need to manipulate an index or a control variable.

The foreach loop offers several advantages over other traditional loops. The syntax of the foreach loop is clearer and more concise (which facilitates code understanding and maintenance).

Furthermore, by not depending on indexes, it reduces the possibility of making errors when accessing collection elements.

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

The basic syntax of a foreach loop in C# is as follows:

foreach (type variable in collection)
{
    // Code to execute for each element in the collection
}
Copied!
  • Type: The data type of the elements in the collection.
  • Variable: The name of the variable representing each element in the iteration.
  • Collection: The collection from which the elements are to be iterated.
  • Instructions to execute: Here you specify the instructions executed in each iteration. These instructions can be any valid C# code, such as assignments, calculations, method calls, etc.

Basic Example

Let’s consider a simple example where a foreach loop is used to iterate over an array of numbers:

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (int number in numbers)
{
    Console.WriteLine(number);
}
Copied!

This foreach loop will print each number in the numbers array on a separate line.

Considerations of the FOREACH Loop

One of the limitations of the foreach loop is that it does not allow modification of the collection being iterated.

Attempting to add or remove elements from the collection inside the foreach loop will result in an InvalidOperationException.

When you need to modify the collection during iteration, a for or while loop may be more suitable.

It is possible to use foreach with collections we create ourselves. For this, our collection must implement the IEnumerable or IEnumerable<T> interface.

This means providing an implementation of the GetEnumerator method that returns an iterator over the elements of the collection.

That is the only requirement for the foreach loop to work.

Although foreach is extremely useful, it can be slightly slower than the equivalent for or while loop. This is because foreach must obtain the Enumerator and call its methods to traverse the collection.

However, the foreach loop also allows for certain optimizations performed by the compiler, which are not available with other collections.

In any case, the difference is almost negligible. In most cases, readability is preferable to efficiency. Only in cases where a calculation is repeated many (millions and millions) of times, might it justify choosing one over the other for performance reasons. And, in that case, you would have to verify both methods.

Practical Examples of the FOREACH Loop