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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access