This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Program Flow Control: The Foreach Loop

The thirtieth part of the C# Fundamentals tutorial continues the multi-part examination of the program flow control commands available to the C# developer. This article examines the foreach loop structure that cycles through each item in a collection.

The Foreach Loop


The .NET framework and the C# programming language allow you to create groups of related objects known as collections. There are various types of collection available, several of which will be described in a later article. One type has already been examined in the tutorial and will be used for demonstrating the use of the foreach loop. This is the array.

Cycling Through a Collection

It is often necessary to cycle through each object or variable in a collection or array when each item is to be processed in turn. The foreach statement provides a looping structure to achieve this. When used, each item in the collection is processed in series until every item has been referenced or the loop has been halted by a break command.

The following example iterates through each value in an array of integers, identifying the largest value:

int[] values = new int[] {1,3,5,7,9,10,8,6,4,2};
int maxValue = int.MinValue;

foreach(int i in values)
    maxValue = i > maxValue ? i : maxValue;
Console.WriteLine("Largest = {0}", maxValue);   // Outputs "Largest = 10"

The syntax for the foreach command is as follows:

foreach(type iterator in collection) command;

The iterator variable is the first item of interest. In the example, this is the 'i' variable. When the loop executes for the first time, the iterator variable is loaded with the value of the first item in the array. For each subsequent iteration, the iterator takes the value of the next item until all of the values have been processed.

NB: If the collection or array contains reference types rather than value types the iterator acts as a reference to each object in turn. This allows each object in the array or collection to be modified during the looping process.

The type section is important. It determines the data type of the iterator during the loop's execution. If the type is incompatible with any item in the collection an exception will occur. For this reason, the type used in the example matches that of the elements of the array, int.

The collection section of the foreach command names the collection or array that is to be cycled through. In the example, this is the 'values' array.

The command section behaves in the same manner as for the for loop described earlier in the tutorial. This is the command to be executed during each iteration. Where the body of the loop includes multiple commands, these are provided in a code block.

Breaking Out of a Loop

The foreach loop is a much simpler control structure than the for loop described previously. However, as with all loops, it does permit the use of the break command to exit from a loop early. The following example demonstrates this with a search for a string in an array.

string[] items = new string[] { "A", "B", "C", "D", "E", "F", "G", "H" };
int pos;

foreach (string s in items)
    if (s == "C")
        Console.WriteLine("C found");           // Outputs "C found"

Completing a Loop Iteration Early

As with the for loop, it is possible to end a single iteration early and continue with the next iteration using the continue command. The following example uses the modulus operator to determine which of the items in the array are odd or even numbers, outputting only odd values.

int[] values = new int[] { 1, 3, 5, 7, 9, 10, 8, 6, 4, 2 };
int maxValue = int.MinValue;

foreach (int i in values)
    if ((i % 2) == 0)

    Console.WriteLine(i);                       // Outputs the odd numbers only
19 February 2007