About This eBook by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required