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.

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

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.

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 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)
{
    count++;
    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:

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

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

public class ForeachRefExample
{
    public static void Main()
    {
        Span<int> storage = stackalloc int[10];
        int num = 0;
        foreach (ref int item in storage)
        {
            item = num++;
        }

        foreach (ref readonly var item in storage)
        {
            Console.Write($"{item} ");
        }
        // Output:
        // 0 1 2 3 4 5 6 7 8 9
    }
}

C# language specification

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

See also