What does foreach loop mean

foreach, in (C# reference)

The statement executes a statement or a block of statements for each element in an instance of the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface. The statement is not limited to those types and can be applied to an instance of any type that satisfies the following conditions:

  • has the public parameterless method whose return type is either class, struct, or interface type,
  • the return type of the method has the public property and the public parameterless method whose return type is Boolean.

Beginning with C# 7.3, if the enumerator's property returns a reference return value ( where is the type of the collection element), you can declare the iteration variable with the or modifier.

At any point within the statement block, you can break out of the loop by using the break statement, or step to the next iteration in the loop by using the continue statement. You also can exit a loop by the goto, return, or throw statements.

If the statement is applied to , a NullReferenceException is thrown. If the source collection of the statement is empty, the body of the loop is not executed and skipped.

Examples

Note

The C# examples in this article run in the Try.NET inline code runner and playground. Select the Run button to run an example in an interactive window. Once you execute the code, you can modify it and run the modified code by selecting Run again. The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

The following example shows usage of the statement with an instance of the List<T> type that implements the IEnumerable<T> interface:

The next example uses the statement with an instance of the System.Span<T> type, which doesn't implement any interfaces:

The following example uses a iteration variable to set the value of each item in a stackalloc array. The version iterates the collection to print all the values. The declaration uses an implicit local variable declaration. Implicit variable declarations can be used with either or declarations, as can explicitly typed variable declarations.

C# language specification

For more information, see The foreach statement section of the C# language specification.

See also