If I use:
var strings = new List<string> { "sample" };
foreach (string s in strings)
{
Console.WriteLine(s);
strings.Add(s + "!");
}
the Add in the foreach throws an InvalidOperationException (Collection was modified; enumeration operation may not execute), which I consider logical, since we are pulling the rug from under our feet.
However, if I use:
var strings = new List<string> { "sample" };
strings.ForEach(s =>
{
Console.WriteLine(s);
strings.Add(s + "!");
});
it promptly shoots itself in the foot by looping until it throws an OutOfMemoryException.
This comes as a suprise to me, as I always thought that List.ForEach was either just a wrapper for foreach or for for.
Does anyone have an explanation for the how and the why of this behavior?
(Inpired by ForEach loop for a Generic List repeated endlessly)
It’s because the
ForEachmethod doesn’t use the enumerator, it loops through the items with aforloop:(code obtained with JustDecompile)
Since the enumerator is not used, it never checks if the list has changed, and the end condition of the
forloop is never reached because_sizeis increased at every iteration.