Why this code throws 'Collection was modified', but when I iterate something before it, it doesn't?
The problem is that the way that List<T>
detects modifications is by keeping a version field, of type int
, incrementing it on each modification. Therefore, if you've made exactly some multiple of 232 modifications to the list between iterations, it will render those modifications invisible as far as detection is concerned. (It will overflow from int.MaxValue
to int.MinValue
and eventually get back to its initial value.)
If you change pretty much anything about your code - add 1 or 3 values rather than 2, or lower the number of iterations of your inner loop by 1, then it will throw an exception as expected.
(This is an implementation detail rather than specified behaviour - and it's an implementation detail which can be observed as a bug in a very rare case. It would be very unusual to see it cause a problem in a real program, however.)