Collection being modified during loop when there is no way it can be C#

The following code's foreach statement throws an InvalidOperationException saying "Collection has been modified. Enumeration operation cannot execute." I don't see how this is possible, seeing as colors can never be modified after it's initialization.

Dictionary<Color, int> colorDictionary = new Dictionary<Color, int>();
//Put stuff in colorDictionary...
int currentBest = 257;
Color replaceColor = Color.Empty;
Dictionary<Color, int>.KeyCollection colors = colorDictionary.Keys;
foreach (Color c in colors)
{
    if (colorDictionary[c] == 0)
    {
        continue;
    }
    if (ColorDistance(color, c) < currentBest)
    {
        replaceColor = c;
        colorDictionary[c]--;
    }
}
Jon Skeet
people
quotationmark

I don't see how this is possible, seeing as colors can never be modified after it's initialization.

It's a view on the dictionary's keys... and you're modifying the dictionary here:

colorDictionary[c]--;

Admittedly that's not actually adding or removing any keys - but it's modifying the dictionary, and the key enumerator is basically sensitive to that.

The simplest fix would be just to create a copy:

IEnumerable<Color> colors = colorDictionary.Keys.ToList();

people

See more on this question at Stackoverflow