V3221. Modifying a collection during its enumeration will lead to an exception.
The analyzer has detected that a collection is being modified during iteration. This may result in an InvalidOperationException
.
The example:
public void AppendMissingNames(List<string> currentNames,
List<string> otherNames)
{
foreach(string name in currentNames)
{
if (!otherNames.Contains(name))
{
currentNames.Add(name);
}
}
}
In the foreach
loop body, the Add
method is called on the currentNames
collection while iterating over the same collection. Modifying currentNames
during iteration will cause the InvalidOperationException
.
The fixed code might look as follows:
public void AppendMissingNames(List<string> currentNames,
List<string> otherNames)
{
foreach(string name in currentNames)
{
if (!otherNames.Contains(name))
{
otherNames.Add(name);
}
}
}
Missing names should be added to otherNames
instead of currentNames
. This ensures that the collection being iterated over remains unchanged.
Take a look at the following example of iterating over a collection using the ForEach
method:
collection.ForEach(name => { collection.Add(name); });
The error is similar to the previous one: the collection being iterated over is modified. To fix this, change the collection where new elements are added:
collection.ForEach(name => { collectionForAppend.Add(name); });
This diagnostic is classified as: