The foreach Statement

One of the most common sources of loop constructs enumerating over a collection of some sort and executing some code for all the elements found. Welcome the foreach statement, which provides you with this functionality.

Before we delve into details, let’s take a look at a few examples. The simplest collection type is the array. Instead of writing a for loop that goes over a range of indices using the array’s Length property as an exclusive upper bound, we can write the following:

int[] primes = new int[] { 2, 3, 5, 7 };foreach (int prime in primes){    Console.WriteLine(prime);}

The foreach statement breaks down into the following pieces:

foreach (type identifier ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.