2

I am trying to run a test generation and passing some of the test outputs to a foreach loop, but every other time I try to run the method it stops and the in in the foreach loop it gives an exception

System.InvalidOperationException occurred in mscorlib.dll

and then the Exception is caught in the try catch and gives the error

Collection was modified; enumeration operation may not execute

I'm not entirely sure why this error is being produced!

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
user3047041
  • 87
  • 2
  • 2
  • 11

1 Answers1

7

You are not allowed to modify a loop's list inside the loop. So create a new list of that same thing:

var predcostssubjForLoop = predcostssubj.ToList();

and then do a

foreach (PredCost pc in predcostssubjForLoop )

but continue to modify predcostssubj inside the loop

As a side note, I suggest you check out the book Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin

Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
  • I'm not quiet sure I follow, could put possible put it in more of a constructive way please? But if I'm thinking correctly I need to created a new loop which is made for the information passed from the original loop? And then I can modify the information from there? As for the book I've just recently bought code complete and I'm slowly making my way through that but thanks. – user3047041 Nov 14 '15 at 00:02
  • Yes, you can not change the contents of a list in the `foreach`, while you are looping through that list. Since this causes the list to change in the `foreach` as well and the `foreach` doesn't know how to handle that... so if you add to the beginning of the list, should the `foreach` go back to the beginning so that it actually goes through each thing in that list... it doesn't know what to do so it fails. Basically, don't modify the list you are looping through while you are looping through it... not sure how much more "constructive" I can make it... – Serj Sagan Nov 14 '15 at 05:28
  • Let me try to make it constructive: It's a common error even for very experienced programmers to try and check an object that they need to modify. We all do it. I don't think Serj is overlooking that. Code late at night, miss getting enough coffee and you'll make every mistake in the book after a few years. :) I just did it and had to look over the right way of thinking again. I've been coding for 10 years and just chuckled at myself, thinking "Of course ... it's obvious I can't check and then modify what I'm testing with." – user1585204 Apr 13 '17 at 17:43