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.
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.
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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 18, 2023 (edit).