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.
foreach (string name in names) { Console.WriteLine(name); }
Try it
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.
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
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.
foreachis awhileloop aroundMoveNext()inside atry/finallythat callsDispose(). Because of that, breaking out early still releases the enumerator. - Closures capture a fresh iteration variable per iteration (since C# 5), unlike a
forcounter. - Value-type elements are copied into the iteration variable. Changing a struct copy does not change the collection; use
forwithreflocals orCollectionsMarshal.AsSpanto modify in place. - Allocation: iterating through
IEnumerable<T>boxes struct enumerators, while iteratingList<T>, arrays and spans directly does not. - Order is the enumerator's order: arrays and lists by index,
Dictionaryin an unspecified order (do not rely on insertion order),SortedDictionaryby key. - Async sequences use
await foreach; add.ConfigureAwait(false)or.WithCancellation(token)on the sequence when needed. - No index. Use
Select((x, i) => ...)or aforloop when you need the position.
Related
- for, yield, while and do, break and continue
- Lessons: foreach, Indexers and iterators, Async streams