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 in expression) embedded-statement
Here, expression
represents ...
Get C# 4.0 Unleashed 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.