Why this matters
Removing items directly from a collection while iterating can cause runtime exceptions. Use safe removal techniques such as ToList().
Verify that collections are not modified directly during iteration. Instead, ensure safe removal techniques such as iterating over a copy or using ToList().
Removing items directly from a collection while iterating can cause runtime exceptions. Use safe removal techniques such as ToList().
Side-by-side examples engineers can pattern-match during review.
foreach (var item in someList)
{
if (item.Condition)
someList.Remove(item);
}
someList.RemoveAll(item => item.Condition);
From the same buckets as this rule.
Check if loops use equality operators (== or !=) in termination conditions. These can lead to infinite loops if the condition is never met exactly. Instead, use relational operators like < or > for safer loop termination.