Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 182 ยท Operators and Control Flow

foreach and Iteration

Learn the C# foreach loop - iterating arrays, lists, strings and dictionaries, the read-only iteration variable, why modifying a collection throws, and getting indexes with Index().

Most loops exist to visit every item of a collection: print every name in a list, add up every price in an array, check every character of a string. You can do that with a for loop and an index, but C# has a loop made for exactly this job. The foreach statement visits each element in turn and hands it to you, without any counter to manage, so there is no off-by-one error to make.

This lesson shows how foreach works on arrays, lists, strings, dictionaries and ranges of numbers, why the iteration variable is read-only, what happens when you change a collection during iteration, how to get an index when you need one (including the .NET 9 Index() method), and what the compiler really does behind the scenes. For counted loops, see while, do-while and for.

The basic form

The syntax is foreach (Type name in collection). The body runs once per element, in order, with name holding the current element.

C# foreach over an array

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.

You can write var instead of the type: foreach (var fruit in fruits). The compiler infers string. Use var when the type is obvious from the right-hand side and the explicit type when it makes the code clearer.

foreach works on anything that can be enumerated: arrays, List<T>, HashSet<T>, Dictionary<TKey,TValue>, string, LINQ results, and your own types (iterators).

C# foreach over a list, a string and a set

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.

A string is a sequence of char values, so you can walk through its characters. The sorted set ignores the duplicate "api" and yields its items in order. Order is a property of the collection, not of foreach: arrays and lists give insertion order, sorted collections give sorted order, and the order of a plain HashSet or Dictionary should not be relied on.

Dictionaries

Iterating a Dictionary<TKey,TValue> gives you KeyValuePair<TKey,TValue> items. Deconstruct them directly in the loop header to get neat names:

C# Looping over a dictionary

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.

We used a SortedDictionary so that the output has a guaranteed order; with a normal Dictionary<string,int> the enumeration order is an implementation detail, so never depend on it. The .Keys and .Values properties let you loop over just one side. More about dictionaries in dictionaries.

The iteration variable is read-only

Inside the body you cannot assign to the iteration variable. The compiler stops you:

C# Assigning to the iteration variable (fails on purpose)

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.

The error is error CS1656: Cannot assign to 'n' because it is a 'foreach iteration variable'. That protects you from believing you modified the array. If you want to change the elements, use an index-based for loop, or build a new collection with LINQ's Select.

C# Changing elements needs for, not foreach

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.

This prints 2, 4, 6 and then 6, 12, 18. One subtlety: the variable is read-only, but if the elements are reference types, you can still change the object the variable refers to, such as setting a property on it. You cannot make the variable refer to a different object. For value-type elements like struct, a property assignment on the iteration variable would change only a copy, which is why the compiler rejects it.

Modifying a collection while iterating

A List<T> keeps a hidden version counter that changes whenever you add or remove items. The enumerator checks that counter at every step. If you changed the list during foreach, the next step throws.

C# Removing during foreach (fails on purpose)

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.

The program ends with Unhandled exception. System.InvalidOperationException: Collection was modified; enumeration operation may not execute. There are safe ways to do this, depending on what you want:

C# Safe ways to remove items

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.

All four print 1, 3, 5 (the first with the extra note (removed 3)). Going backwards works because removing the item at index i only shifts the items that come after it, which you have already visited. Dictionary and HashSet allow removing items during enumeration since .NET Core 3.0, but the safe rule "do not change the structure of a collection while looping over it" is the one to remember.

Getting an index while iterating

Sometimes you need both the item and its position, for example to number the lines of a list. You have three options.

C# Three ways to get the index

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.

Index() returns tuples named Index and Item, so deconstruction gives you clean names. It is more readable than a manual counter, at the price of a small enumerator allocation. Older code uses Select((item, i) => ...) for the same purpose.

Do not confuse the LINQ method Index() with the Index type of the ^1 syntax; the latter is covered in ranges and indices.

Iterating over a range of numbers

C# has no foreach (i in 1..10), but Enumerable.Range(start, count) works well when the loop body is simple:

C# Enumerable.Range and Reverse

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.

For hot loops with millions of passes a plain for is faster, since it avoids creating an enumerator.

Exiting early

You can use break to stop the loop and continue to skip to the next element. Both work exactly as in other loops; see break, continue, goto and return.

C# break and continue in foreach

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.

What the compiler does

foreach is syntax sugar. For an array, the compiler generates an indexed for loop. For other collections it calls GetEnumerator() and loops on MoveNext(), reading Current, and disposes the enumerator in a finally block. Roughly:

C#
// foreach (var x in list) { Use(x); } becomes:
using (var e = list.GetEnumerator())
{
    while (e.MoveNext())
    {
        var x = e.Current;
        Use(x);
    }
}

The "duck typing" rule is that your type does not need to implement IEnumerable<T> at all: having a public GetEnumerator() method that returns something with MoveNext() and Current is enough. List<T> exploits this by returning a struct enumerator, which avoids allocations. If you iterate through the IEnumerable<T> interface instead, the struct is boxed. These details matter in hot code; the iterators lesson explains how to write your own enumerators.

Iterating a null collection throws NullReferenceException, and iterating an empty one simply runs the body zero times. Return empty collections instead of null from your methods.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you assign to the iteration variable of a foreach loop?

    The iteration variable is read-only. Assigning to it is error CS1656 at compile time.
  2. 2. What does a foreach over a List<int> do if the body calls list.Add(1)?

    The list's enumerator detects that the collection changed and throws InvalidOperationException ("Collection was modified; enumeration operation may not execute").
  3. 3. Which is the best way to remove all even numbers from a List<int>?

    RemoveAll takes a predicate and removes matching items safely and efficiently in one pass.
  4. 4. What does foreach (var (i, item) in names.Index()) give you?

    Enumerable.Index() (added in .NET 9) yields (Index, Item) tuples, which you can deconstruct into the position and the element.
  5. 5. In which situation is a for loop better than foreach?

    foreach cannot assign to its variable, so replacing array elements needs an index. For reading, foreach is simpler and safer.

Summary

  • foreach (var item in collection) visits every element without a counter and works with arrays, lists, sets, dictionaries, strings and anything enumerable.
  • The iteration variable is read-only; use for or LINQ to change elements.
  • Changing a collection's structure inside foreach throws InvalidOperationException; use RemoveAll, iterate over a copy, loop backwards, or build a new collection.
  • Dictionaries yield key/value pairs that you can deconstruct: foreach (var (key, value) in dict).
  • Enumerable.Index() (.NET 9) gives (Index, Item) tuples when you need positions.
  • The compiler turns foreach into an enumerator loop (or an indexed loop for arrays), and a custom type only needs a suitable GetEnumerator() method.

Next: break, continue, goto and return