Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

foreach, in

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

where:

type
The type of identifier.
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.
expression
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.

statement
The embedded statement(s) to be executed.

Remarks

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:

See Also

C# Keywords | Iteration Statements | C. Grammar

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft