Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Keywords and Statements

The foreach statement

Reference for C# foreach: iterating arrays, lists, dictionaries and strings, the iteration variable, deconstruction, await foreach and modification errors.

foreach runs its body once for every element of a collection. It works with arrays and with any type that has a public GetEnumerator() method returning an object with MoveNext() and Current (usually by implementing IEnumerable<T>). The compiler generates the enumerator calls and disposes the enumerator for you.

The iteration variable is read-only inside the body. You cannot assign to it, and for most collections you cannot add or remove elements while looping. Use for if you need an index or want to change the collection.

C#
foreach (string name in names)
{
    Console.WriteLine(name);
}

Try it

C# Arrays, strings, dictionaries and tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Changing a collection while looping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
foreach (Type name in collection) statement
foreach (var name in collection) statement
foreach (var (a, b) in collection) statement
foreach (ref readonly T item in span) statement   // ref iteration
await foreach (var item in asyncSequence) statement
Name Description
Type / var The iteration variable type. An explicit type that differs from the element type applies an explicit cast to each element and can throw InvalidCastException.
collection An expression whose type has a suitable GetEnumerator() (or implements IEnumerable / IEnumerable<T>, or IAsyncEnumerable<T> for await foreach).

Errors: assigning to the iteration variable fails with CS1656. Modifying a List<T>, Dictionary<TKey,TValue> or similar during enumeration makes the next MoveNext() throw InvalidOperationException ("Collection was modified"). A null collection throws NullReferenceException.

Usage notes

  • Equivalent code. foreach is a while loop around MoveNext() inside a try/finally that calls Dispose(). Because of that, breaking out early still releases the enumerator.
  • Closures capture a fresh iteration variable per iteration (since C# 5), unlike a for counter.
  • Value-type elements are copied into the iteration variable. Changing a struct copy does not change the collection; use for with ref locals or CollectionsMarshal.AsSpan to modify in place.
  • Allocation: iterating through IEnumerable<T> boxes struct enumerators, while iterating List<T>, arrays and spans directly does not.
  • Order is the enumerator's order: arrays and lists by index, Dictionary in an unspecified order (do not rely on insertion order), SortedDictionary by key.
  • Async sequences use await foreach; add .ConfigureAwait(false) or .WithCancellation(token) on the sequence when needed.
  • No index. Use Select((x, i) => ...) or a for loop when you need the position.