C# Collection Was Modified Exception

Warning

You encountered the "collection was modified" exception in your program. You have a collection such as a TreeView, and you are removing items such as TreeNode controls in a foreach loop. Here we see ways you can solve this exception in C# and what it means.

Collection Was Modified exception

Here we examine some situations that can cause this exception, and then some ways to fix it. The example below demonstrates a TreeNodeCollection and a foreach loop that tries to remove an item, but raises an exception.

=== Code that causes exception (C#) ===

foreach (TreeNode treeNode in treeView1.Nodes)
{
    if (treeNode.Nodes.Count == 0)
    {
        treeNode.Remove();
    }
}

Description of the example. It uses Nodes collection. This is a collection of TreeNode objects that are nested in the TreeView. The foreach loop iterates over each item in the Nodes collection. We call the Remove method, and it tries to modify the collection during the loop.

Understanding the exception

When you run the above code in a Windows Forms application, you will see an exception. The code will produce an error like the following. In this specific case, we shouldn't try to handle the exception, but should fix our code.

System.InvalidOperationException was unhandled
  Message="Collection was modified; enumeration operation may not execute."
  Source="mscorlib"
  StackTrace:
       at System.ThrowHelper.ThrowInvalidOperationException(...)
       at System.Collections.Generic.List`1.Enumerator.MoveNext()

Description of the error. All the InvalidOperationException means is that your code does something bad. The Message on the second line is the secret we need to know. The message says "Collection was modified" and that the enumeration won't work. This is because we are changing the elements in the collection while looping over it with foreach.

What foreach does. It queries the enumerator and asks for the next element. In our example, the enumerator's state becomes invalid when we remove the item. An enumerator has to store some data indicating where it currently is.

Fixing the exception

This problem often occurs in Windows Forms control collections. I was puzzled by it when trying to remove nodes from a TreeView control. What follows is code that accomplished the goal in the first example, without raising an exception.

=== Code that fixes exception (C#) ===

List<TreeNode> treeList = new List<TreeNode>();
foreach (TreeNode treeNode in treeView1.Nodes)
{
    if (treeNode.Nodes.Count == 0)
    {
        treeList.Add(treeNode);
    }
}

foreach (TreeNode treeNode in treeList)
{
    treeNode.Remove();
}

Description of the example. We can store a List of TreeNode objects separately. We built this up with the TreeNode controls that we wish to remove. In the example, we want to remove TreeNode controls with no children. It is just solid, working code, which is the very best kind.

Summary

Here we saw how you can remedy the Collection Was Modified exception. To remove items from a collection, such as List or TreeNodeCollection, first add references to all the objects you want to remove in a new List. Then, remove those items when iterating over the temporary collection. Finally, you can find more details on the TreeView control on this site.

See TreeView Tutorial 1.

See Exception Content.

© 2007-2010 Sam Allen. All rights reserved.

Dot Net Perls  Sam Allen