BlackWasp
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

Collections

The .NET framework and the C# programming language allow the programmer 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 in this tutorial. One collection 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 exited early with 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"

Let's review the syntax of the foreach loop to understand how the above example works. The only syntax for the foreach command is as follows:

foreach(type iterator in collection) command;

The iterator variable is the first item of interest. In our 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 in the array until all of the integer 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. This determines the data type that is to be used for the iterator during the loop's execution. If the type of the iterator is not compatible with the type of any item in the collection then 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 our example, this is the 'values' array. Note that for arrays, no square brackets are used after the variable name. This is because the array as a whole is being processed rather than any specific element.

The command section behaves in the same manner as for the for loop described earlier in the C# Fundamentals tutorial. This is the actual command to be executed during each iteration. Where the body of the loop includes multiple commands, these must be provided in a code block surrounded by the brace characters, { and }.

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 when continuing looping would be inefficient. The following example demonstrates this with a simple search for a specific 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"
        break;
    }
}

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 by 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 and outputs only the 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)
    {
        continue;
    }

    Console.WriteLine(i);                       // Outputs the odd numbers only
}
Link to this Page19 February 2007
RSS RSS Feed