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 the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects. The statement takes the following form:
foreach (type identifier in expression) statement
- The type of identifier.
- The iteration variable that represents the collection element. If the iteration variable is a value type, it is effectively a read-only variable that cannot be modified.
- Object collection or array expression. The type of the collection element must be convertible to the identifier type. Do not use an expression that evaluates to null.
Evaluates to a type that implements IEnumerable or a type that declares a GetEnumerator method. In the latter case, GetEnumerator should either return a type that implements IEnumerator or declares all the methods defined in IEnumerator.
- The embedded statement(s) to be executed.
The embedded statements continue to execute for each element in the array or collection. After the iteration has been completed for all the elements in the collection, control is transferred to the next statement following the foreach block.
For more information on the foreach keyword, including code samples, see the following topics: