Tier 1
Series 8
8E: The Cargo Shift
"You can't reorganize the cargo hold while you are actively counting the boxes. You will lose count or get crushed. You cannot remove items from a list while running a "Foreach" loop on it."
The Concept: Collection Modification
**InvalidOperationException** occurs when you modify a list (Add/Remove) inside a `foreach` loop. The loop relies on the list size staying constant.
* **The Fix:** Use a backwards `for` loop (i--) OR create a separate list of items to remove.
* **The Fix:** Use a backwards `for` loop (i--) OR create a separate list of items to remove.
Red Flag Detected
The Audit: The Self-Destruct Loop
Ask the AI to remove dead enemies from the list.
foreach (Enemy e in enemies) {
if (e.isDead) {
// FRAGILE CODE
// This throws an error immediately.
enemies.Remove(e);
}
}
This is a "Collection Crash." You cannot modify the list `enemies` while the `foreach` iterator is reading it.
Elite Telemetry
Research shows "Elite" teams achieve 15% faster lead times by keeping AI on a "very tight leash."
- Small Batches Solving one problem at a time prevents logic drift.
- Modular Design Localizing the "blast radius" of AI changes.
- Tight Loops Rapid iteration with constant code review.
The Mechanic's Correction
Corrective Protocol
// AUDIT PASS: Iterate backwards to remove safely.
for (int i = enemies.Count - 1; i >= 0; i--) {
if (enemies[i].isDead) {
enemies.RemoveAt(i);
}
}
Your Pilot Command
> A skilled Mechanic directs the AI to use a reverse For loop.