The foreach Statement

The foreach statement allows you to iterate through all the items in an array or other collection, examining each item in turn. The syntax for the foreach statement is:

foreach (type identifier in expression)statement

You can update Example 10-1 to replace the second for statement (the one that iterates over the contents of the populated array) with a foreach statement, as shown in Example 10-3.

Example 10-3. You can use the foreach statement to iterate through an array instead of using a for loop

foreach (int i in myIntArray)
{
    Console.WriteLine("The value is {0}.", i);
}

The output will be nearly the same. Note that in this case, though, i doesn’t represent the index of the array element; it represents the array element itself. In Example 10-1, we used i to output the index as well as the value. Here, that’s not an option. If you specifically want to output the index as well as the value, you’re better off using the for loop.

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.