Code:
public List<Interfaces.Test> IJ_;
IEnumerator<Interfaces.Test> Ij_ = Objects.GetEnumerator();
int count = IJ_.Count;
Ij_.MoveNext();
for (int x = 0; x < count; x++)
{
if (x >= count)
break;
Test MyBase = IJ_.Current;
if (MyBase == null)
obj_.MoveNext(); //here the error
}
Error:
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
Please help me.
As the error says, the collection is modified during the iteration, which is an illegal operation.
Either way, the right way to iterate using an enumerator is this:
You should make sure that you don’t add, remove or set items in the collection during the iteration (not in the loop, and not in a different thread). Changing an element’s inner state is allowed.
If the enumerator is your implementation, and the error still occurs after assuring that the collection is not modified during the iteration, it might be helpful to post the enumerator’s code as well.