C# foreach

Summary: in this tutorial, you’ll learn how to use the foreach statement to iterate over array elements.

Using foreach with a single-dimensional array

To iterate over elements of a single-dimensional array, you can use the for statement. However, the foreach statement provides a more simple and clean way to do so.

The following uses the for statement to iterate over elements of an array:

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

for (int i = 0; i < scores.Length; i++)
{
    Console.Write($"{scores[i]} ");
}Code language: C# (cs)

Output:

5 2 1 3 4Code language: C# (cs)

In this example, we access the elements of the scores array using an index specified by the variable i. The variable i starts at the index of the first element (0) and ends at the index of the last element (Length – 1). In each iteration, the variable i is increased by one. Therefore, the code iterates over all the array elements.

The for statement works fine but it’s quite verbose and error-prone.

For example, if you don’t control the variable i properly, you’ll get an error of accessing an element at an invalid index.

The following example uses the foreach statement to iterate over the elements of the scores array:

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

foreach (int score in scores)
{
    Console.Write($"{score} ");
}Code language: C# (cs)

Output:

5 2 1 3 4

In this example, the foreach statement processes the elements in the scores array in increasing index order starting from the index 0 and ending with the index Lengh - 1. In each iteration, the foreach statement assigns the current element to the score variable.

Note that you can use the break and continue statements in the foreach statement as the for statement.

The foreach statement doesn’t allow you to change the array elements. For example, the following cause an error because it attempts to change the values of the array elements in a foreach loop:

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

foreach (int score in scores)
{
    score = score * 2; // error
    Console.Write($"{score} ");
}Code language: PHP (php)

To change the array element inside the loop, you need to use the for statement. For example:

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

for (int i = 0; i < scores.Length; i++)
{
    scores[i] *= 2;
    Console.Write($"{scores[i]} ");
}Code language: HTML, XML (xml)

Output:

10 4 2 6 8

The following table summarizes the differences between foreach and for statements:

foreachfor
Clean and simpleComplex but flexible
Iterate all elementsIterate all or a subset of elements
The elements are read-onlyThe elements are changeable

Using the foreach statement with a multidimensional array

For a multidimensional array, the foreach statement increases the indices of the rightmost dimension first and then the next left dimension, and so on to the left. For example:

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

foreach(var e in matrix)
{
    Console.Write($"{e} ");
}Code language: C# (cs)

Output:

1 2 3 4 5 6Code language: C# (cs)

In this example, we have a two-dimensional array with two rows and three columns. The foreach statement iterates elements from rows 0 to 1. For each row, it iterates the elements from columns 0 to 3.

If you want to control the order in which to access the array elements, you can use a nested loop with the for statement.

Summary

  • Use the foreach statement with one-dimensional arrays to iterate through the array elements.
  • For a multidimensional array, use the for statement to control the order in which you want to access the array elements.
Was this tutorial helpful ?