C# Foreach Loop

The foreach loop is built for going through every item in a collection such as an array or a list. You don't manage a counter or worry about the length, so there is no risk of going out of bounds. It reads almost like plain English: for each item in the collection, do something.

The foreach Loop

A foreach loop declares a temporary variable that holds one item at a time. On each pass, the variable is filled with the next element of the collection until every element has been visited.

Looping over an array

string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Here the variable fruit becomes "apple", then "banana", then "cherry" on successive passes, printing each one. You never touch an index, so the loop is short and safe.

foreach vs for

Featureforeachfor
Needs a counterNoYes
Can change item order or indexNoYes
Best forReading every itemPrecise control over the index
Note: You cannot use foreach to add or remove items from the collection while looping over it, and you cannot reassign the loop variable to change the collection. If you need to modify by position, use a for loop instead.

Using var for the Item

You can let the compiler figure out the item type by writing var. This is common and keeps the line shorter, especially when the type name is long.

foreach with var

int[] scores = { 90, 85, 100 };
foreach (var score in scores)
{
    Console.WriteLine("Score: " + score);
}