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.
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.
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
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.
foreach
loop, we correctly loop over the ints in the List
.foreach
loop, we create an error by trying to add an item to the List
while in a foreach
.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...
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.
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.