According to the documentation for IEnumerator<T>
, the MoveNext()
method will throw an InvalidOperationException
if the collection is modified after the enumerator was created.
Even if you implement your own enumerator that does not behave this way (including a select few included in .NET), you should never modify a collection inside of a foreach
statement which is enumerating the elements of that collection, since that is an immediate visual indication that your code is likely to throw an exception.