11.3. Looping with the foreach keyword

C# comes with a new and convenient foreach keyword used for looping. What you can do with foreach, you can do with for (or while), but foreach is very convenient indeed for certain scenarios. For instance, you do not need to create a temporary loop counter variable to keep track of looping. foreach works only for repeating a bunch of statements (or looping through) once for every element of an array or object collection. [5]

[5] I will cover only using foreach for arrays in this section. You can iterate through a collection type using foreach too, but quite some work has to be done to prepare a class so that you can iterate through it using foreach. This special class has to implement System.Collections.IEnumerable ...

Get From Java to C#: A Developer's Guide 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.