0

One would imagine this would be a pretty simple task, yet I'm getting a System.InvalidOperationException when I run this code:

Dictionary<string, bool> TableExists = new Dictionary<string, bool>(); //... fill the dictionary foreach(string value in TableExists.Keys){/*Do something*/} 

It is supposed to iterate through the keys of the dictionary TableExists, but I get the Invalid Operation Exception at the foreach line. Am I using any Dictionary operations incorrectly? What is the proper way to work through the keys of a C# Dictionary if so?

Edit:

Yes, I was attempting to change some values corresponding to dictionary keys, getting a Collection was modified error.

6
  • 6
    Nothing wrong with the piece of code you have shown. Something else must be going on. Commented Jun 16, 2015 at 21:14
  • 4
    What's in the Do something could be material to your question. Commented Jun 16, 2015 at 21:15
  • What's the stack trace? Commented Jun 16, 2015 at 21:15
  • It may have to do with this error then: stackoverflow.com/questions/1582285/… . Thanks for the help. Commented Jun 16, 2015 at 21:16
  • Don't downvote me bro, don't downvote me! Commented Jun 16, 2015 at 21:18

1 Answer 1

9

Certain operations are not allowed within foreach (emphasis mine):

The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects.

If you are trying to add or remove the dictionary elements within foreach you may get

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

Sign up to request clarification or add additional context in comments.

3 Comments

Who will add more? :D
How on earth did this get 8 upvotes within a minute when the answer was a comment?
Yes, this is an error I'm getting. Thanks for the help. Will mark correct when I get the ability to do so.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.