Foreach Loop
The foreach loop is yet another looping structure in C# which is specially designed for arrays, lists, and collections.The foreach loop cycles through each of the elements, placing the element’s value into a temporary variable. You can access the element’s value through that temporary variable. Below shows the syntax of using a foreach loop.
foreach (datatype temporaryVar in array)
{
code to execute;
}
The temporaryVar is the variable that will hold the values of the elements of the array. The temporaryVar should have a data type capable of storing the value of an element in the array. For example, if you have to cycle through an array of int numbers, the data type of the temporary variable should be int as well or any data type that can store int such as double or long. In objects inheriting other objects, the type of a variable could be the type of any object it inherits. Then we write the in keyword and then the name of the array in which the foreach loop will get the values one by one. Below is an example of using the foreach loop.
using System;
namespace ForeachLoopDemo
{
public class Program
{
public static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int n in numbers)
{
Console.WriteLine("Number {0}", n);
}
}
}
}
Example 1 – Using the foreach Loop
Number 1 Number 2 Number 3 Number 4 Number 5
The program declares a 5-element array with values of 1 to 5 (line 9). Line 11 starts the foreach loop. We declare a temporary variable that will hold the values from the numbers array. For each loop cycle of the foreach loop, the temporary variable n extracts a value from the numbers array. The foreach loop gets the value from the first element up to the last element. Unlike a for loop, you cannot control the sequence of how the foreach loop gets the value unless you use custom iterators which is an advanced topic. The foreach loop is good if you want to get each of the values in an array. After getting the value of an element in the array, we print the value of the temporary variable.
There’s one downfall when considering using foreach loops. foreach loops are limited to accessing or reading the data. They cannot modify the elements of an array. To understand this, the code below tries to increment the value of each of the element of an array.
int[] numbers = { 1, 2, 3 };
foreach(int number in numbers)
{
number++; // This will cause an error
}
Run the program and it will give you an error. If you want to modify each element, then use a for loop instead.
int[] numbers = { 1, 2, 3 };
for (int i = 0; i < number.Length; i++)
{
numbers[i]++;
}
C# and .NET uses the IEnumerable interface behind the scenes when using a foreach loop. I previously said that foreach loops can be used on arrays, lists and collections. All of them implement the IEnumerable interface. This allows them to be enumerated by the foreach loop. I will not be discussing IEnumerable for now as we haven’t reached the Object Oriented Programming and interface lessons yet.