O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

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

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

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