Out of sync error when iterating over a Dictionary

So, I am getting the following error (that I have not yet run into) when iterating over a Dictionary in my code. It’s a simple piece of code that iterates through the dictionary and resets the player scores inside it. Here’s there code

void resetScore () {
		foreach (KeyValuePair<string, int> pair in points) {
			points[pair.Key] = 0;
		}
	}

And here is the error

InvalidOperationException: out of sync
System.Collections.Generic.Dictionary`2+Enumerator[System.String,System.Int32].VerifyState () (at /Applications/buildAgent/work/3df08680c6f85295/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:912)
System.Collections.Generic.Dictionary`2+Enumerator[System.String,System.Int32].MoveNext () (at /Applications/buildAgent/work/3df08680c6f85295/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:835)
gameManager.resetScore () (at Assets/code/gameManager.cs:85)
gameManager.turnRound () (at Assets/code/gameManager.cs:44)
gameManager.scoreUpdate (System.String scoringPlayer, Int32 scoreValue) (at Assets/code/gameManager.cs:80)
goal.OnTriggerEnter (UnityEngine.Collider obj) (at Assets/code/goal.cs:10)

I’m not entirely sure what this error means or how to go about dealing with it. Any help is most appreciated.

One of the restrictions of a foreach loop is that you can’t change the underlying thing you’re iterating over. If you change a dictionary while you’re iterating through it, the program has no idea if it’s getting out of sync and could end up for instance in an infinite loop.

Instead, you can get a list of the keys in the dictionary and iterate over that list. Since you won’t be changing that list, just using it to change the dictionary, there’s no chance of getting out of sync.

Added to @Julien’s answer, instead of using:

foreach (string s in dict.Keys) {
  dict  ~~= ...~~

Use:
List keys = new List (dict.Keys);
foreach (string key in keys) {
dict [key] = …

foreach (string s in dict.Keys.ToList()) {
dict = …
Would be the simplest solution I guess

Before I saw @furic 's answer to create a list out of the keys, I did this. Thought someone might find it useful.

Item[] items = new Item[m_dict.Count];
m_dict.Values.CopyTo(items, 0);

foreach (Item item in items)
{
    Destroy(item);
    m_dict.remove(item);
}