C# Academy · Lesson

Common Iteration Mistakes

Modifying while iterating.

Lesson 4 of 413 steps

Common Iteration Mistakes is a free C# Academy lesson on CoddyKit. This is lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, and your progress syncs across the web and the CoddyKit app. The C# Academy course includes 4 lessons in total.

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
}

The Safe Fix

To remove while looping, iterate over a copy, or collect items first and remove them after.

Looping over list.ToList() gives you a separate snapshot to walk.

var list = new List<int> { 1, -2, 3, -4 };
foreach (var n in list.ToList())
{
    if (n < 0) list.Remove(n);
}
Console.WriteLine(string.Join(",", list));

Off-by-One in for Loops

With a manual for loop, using <= instead of < reads past the end.

Valid indexes go from 0 to Length - 1, so the condition should be i < Length.

for (int i = 0; i <= arr.Length; i++) // BUG: <= goes too far
{
    Console.WriteLine(arr[i]);
}

IndexOutOfRange

That off-by-one causes an IndexOutOfRangeException.

foreach avoids this entirely because it never uses an index. Prefer it when you only need to read items.

string[] arr = { "a", "b", "c" };
for (int i = 0; i < arr.Length; i++) // correct: < Length
{
    Console.WriteLine(arr[i]);
}

Expecting foreach to Change Items

Assigning to the loop variable does not change the collection, and for value types it is a copy anyway.

To update items, use a for loop with indexing.

int[] nums = { 1, 2, 3 };
for (int i = 0; i < nums.Length; i++)
{
    nums[i] = nums[i] * 10;
}
Console.WriteLine(string.Join(",", nums));

Null Collection

Calling foreach on a null reference throws a NullReferenceException.

An empty collection is fine, but null is not. Check or initialize before looping.

List<int> data = null;
if (data != null)
{
    foreach (var x in data) Console.WriteLine(x);
}

Variable Scope Confusion

The loop variable exists only inside the loop body.

Trying to use it after the loop is a compile error, because it is out of scope once the loop ends.

foreach (var n in nums)
{
    Console.WriteLine(n);
}
// Console.WriteLine(n); // ERROR: n not in scope here

Forgetting Braces

Without braces, only the next single statement belongs to the loop.

This can silently break logic. Always use braces for multi-line bodies to keep intent clear.

foreach (var n in nums)
    Console.WriteLine(n);
    Console.WriteLine("runs once, not per item");

Infinite Risk in while

Unlike foreach, a while loop can run forever if its condition never becomes false.

Always make sure something inside the loop moves toward the exit condition.

int i = 0;
while (i < 3)
{
    Console.WriteLine(i);
    i++; // forgetting this would loop forever
}

Picking the Right Loop

Read every item, no index needed → foreach.

Need the index or must modify in place → for. Repeat until a condition changes → while.

Quick Check

Test what you learned about iteration mistakes.

Recap

You learned to avoid modifying a collection during foreach, off-by-one errors with <=, null collections, and scope confusion.

Choose foreach to read, for to modify by index, and while for condition-based loops with a clear exit.

Free to start

Learn C# with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
93
Lessons
346

Frequently Asked Questions

Is the “Common Iteration Mistakes” lesson free?

Yes — the full text of “Common Iteration Mistakes” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO. The C# Academy course includes 4 lessons in total.

What will I learn in “Common Iteration Mistakes”?

Modifying while iterating. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

How long does the “Common Iteration Mistakes” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

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