foreach, in (C# Reference)

The foreach 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 foreach 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 GetEnumerator method whose return type is either class, struct, or interface type,
  • the return type of the GetEnumerator method has the public Current property and the public parameterless MoveNext method whose return type is Boolean.

At any point within the foreach 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 foreach loop by the goto, return, or throw statements.



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 foreach statement with an instance of the List<T> type that implements the IEnumerable<T> interface:

var fibNumbers = new List<int> { 0, 1, 1, 2, 3, 5, 8, 13 };
int count = 0;
foreach (int element in fibNumbers)
    Console.WriteLine($"Element #{count}: {element}");
Console.WriteLine($"Number of elements: {count}");

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

Span<int> numbers = new int[] { 3, 14, 15, 92, 6 };
foreach (int number in numbers)
    Console.Write($"{number} ");

C# language specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See also

The foreach statement (C# language specification)
Using foreach with Arrays
Iteration Statements
C# Keywords
C# Reference
C# Programming Guide