A collection is changed inside a foreach over it, which throws on the next step

tx0/csharp:modified-while-iteratingdefaultwarningreliability/collectionsdepth fastbug

What it finds

foreach (var x in list) { list.Remove(x); } changes the list under its enumerator, which throws InvalidOperationException when the loop moves on. Changes followed directly by break or return are left alone, since the loop does not continue. Iterate over a copy, or collect the changes and apply them after the loop.

From the rule's source, modified_while_iterating.rs.

Example from the rule's tests
using System.Collections.Generic; class Cleanup{    void Run(List<string> names, Dictionary<string, int> counts)    {        foreach (var name in names)        {            if (name.Length == 0)            {                names.Remove(name);tx0 reports: names is changed with Remove while a foreach iterates over it            }        }        foreach (var name in names)        {            if (name == "x")            {                names.Remove(name);                break;            }        }        foreach (var name in names.ToArray())        {            names.Remove(name);        }    }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/csharp:modified-while-iterating" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/csharp:modified-while-iterating] reason="..."

tx0 explain tx0/csharp:modified-while-iterating shows the same in the terminal. Found a false positive? Report it.