0Pricing
C# Academy · Lesson

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

  1. The foreach Loop
  2. Iterating Collections
  3. break and continue
  4. Common Iteration Mistakes
← Back to C# Academy