I was fiddling around with Unity3D (and C#) and I ran into the following error messages:
InvalidOperationException: Collection was modified; enumeration operation may not execute.
System.Collections.Generic.List`1+Enumerator[UnityEngine.UI.Toggle].VerifyState () (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:778)
System.Collections.Generic.List`1+Enumerator[UnityEngine.UI.Toggle].MoveNext () (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:784)
The stacktrace pointed to a
foreach loop in which I was actually toggling a boolean property of a List member. Quite harmless really. While debugging I found out that the statement wasn't really as innocuous as it seemed. The change in the property was triggering a listener to invoke another function which was removing an element from the List I was looping through. This consequently led to C# complaining that it was looping through a List (the Collection in the error message) that was now not the same as it was when the loop began.
One way to fix (workaround) this would be to avoid using a
foreach loop and use a simple
while and allow for the length of the List varying in the middle of the loop, etc.
But the better way is to avoid removing elements from the Collection in the middle of the loop. This is what I did by setting a flag before entering the loop and unsetting it after.
Hope this helps someone out there :)