Home
C#
foreach List: Loop Over List Elements
Updated May 18, 2023
Dot Net Perls
Foreach, List. With foreach we can loop over the items in a List. This works just like the for-loop, but with simpler syntax. But there is a limitation.
List
An exception. We cannot modify a List while we use foreach on it. A "Collection was modified" exception will be thrown. Foreach requires the collection not change under it.
Required output. Consider a list that has 3 elements. In our foreach-loop, we want to safely iterate over the 3 elements in order.
10, 100, -1 Iterations: 10 100 -1
Foreach example. This example has 2 parts. It shows an exception that can occur when using for each on a List. In our code, it is best to avoid this exception.
Part 1 In the first foreach loop, we correctly loop over the ints in the List.
foreach
Part 2 In the second foreach loop, we create an error by trying to add an item to the List while in a foreach.
Exception
Important We must not modify a List inside a foreach-loop on that List. Other Lists can still be modified though.
using System; using System.Collections.Generic; List<int> list = new List<int>(); list.Add(10); list.Add(100); list.Add(-1); // Part 1: we can loop over list items with foreach. foreach (int value in list) { Console.WriteLine(value); } Console.WriteLine("::DONE WITH PART 1::"); // Part 2: this will cause an exception. foreach (int value in list) { list.Add(0); }
10 100 -1 ::DONE WITH PART 1:: Unhandled Exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute. at System.ThrowHelper .ThrowInvalidOperationException(ExceptionResource resource) at System.Collections. Generic.List`1.Enumerator.MoveNextRare() at System.Collections. Generic.List`1.Enumerator.MoveNext() at Program.Main() in...
A solution. How can we modify a List while looping over it? There is a solution: we can use a for-loop. The for-loop has no "Collection was modified" limitation.
for
A summary. The foreach-loop is a way to simplify syntax in programs. But it is not always perfect—it has a limitation that we cannot modify an underlying collection.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 18, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen