9.6. The foreach Statement

The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through a collection to get the desired information, but, to avoid unpredictable side effects, you should not use it to change the contents of the collection. The statement takes the following form:

foreach (type identifier in expression) statement

where

  • type is the type of identifier.

  • identifier is the iteration variable that represents the collection element.

  • expression is the object collection or array expression. The type of the collection element must be convertible to the identifier type.

  • statement is the embedded statement(s) to be executed.

The embedded statements ...

Get .NET for Java Developers: Migrating to C# 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.