Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio .NET
Reference
Visual C# Language
C# Keywords
Statements
foreach, in

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2003/.NET Framework 1.1

Other versions are also available for the following:
C# Programmer's Reference
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

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker