Collections · interview question
What happens when this code runs?
What does this code output?Medium
var list = new List<int> { 1, 2, 3 };
foreach (var x in list)
{
if (x == 2) list.Remove(x);
}
Console.WriteLine(list.Count);Answer and explanation
Correct answer
A. It throws InvalidOperationException.
Why
List<T> tracks a version number; modifying it during foreach makes the enumerator throw "Collection was modified". Use list.RemoveAll(x => x == 2), iterate a copy, or loop backwards with an index.
Test yourself on Collections
A free test with instant, explained results. No account needed.