Hi all,
has anyone any idea why I get an InvalidOperationException in this case?

Dictionary<char, bool> dict = new Dictionary<char, bool>(6);
            dict.Add('A', false);
            dict.Add('B', false);
            dict.Add('C', true);
            // this works
            dict['A'] = true;
            // foreach gives an InvalidOperationException 
            foreach (KeyValuePair<char, bool> KV in dict)
            {
                dict[KV.Key] = true;
            }

Recommended Answers

All 2 Replies

That code is modifying the underlying collection inside of the foreach. In this case it doesn't hurt anything per se but there is probably a reason where this could break something thus the exception. I usually build lists of items I intend to modify before/after a foreach. Here is one way of doing it but i'm sure there is a more efficient way:

private void button4_Click(object sender, EventArgs e)
    {
      Dictionary<char, bool> dict = new Dictionary<char, bool>(6);
      dict.Add('A', false);
      dict.Add('B', false);
      dict.Add('C', true);
      // this works
      dict['A'] = true;
      // foreach gives an InvalidOperationException 
      List<char> lst = new List<char>();

      foreach (KeyValuePair<char, bool> KV in dict)
      {
        lst.Add(KV.Key);
      }
      foreach (char c in lst)
      {
        dict[c] = true;
      }
    }

I can't think of a good reason off hand why changing the value of a dictionary item would matter

[edit]Ah the KeyValuePair is a struct and not a class so it is not modifying a reference, it has to create a new struct from the looks of it thus changing the collection inside of a foreach() and throwing an exception. I guess that does make sense now[/edit]

Thanks for the reply Scott!
You clarified it!
I also circumvented the problem by using a List as you did but I was still wondering why the Dictionary approach was not working.
Needed this for a tiny language with only 6 char variables to construct logical expressions. My "compiler" would parse those expressions and build truth tables out of it. Has no great use, but I like to explore how computers "think". Did you know there are at least 30 interpretations of the word "yes"? Todays computers still have a lot to learn.:(

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.