Common Iteration Mistakes
Modifying while iterating.
Iteration Pitfalls
Loops are simple, but a few mistakes trip up beginners again and again.
In this lesson we look at the most common iteration errors and how to avoid them.
Modifying While Iterating
The biggest mistake: changing a collection while you foreach over it.
Adding or removing items during iteration throws an InvalidOperationException at runtime.
foreach (var n in list)
{
if (n < 0) list.Remove(n); // ERROR at runtime
}All lessons in this course
- The foreach Loop
- Iterating Collections
- break and continue
- Common Iteration Mistakes