views:

51

answers:

3

Hi All,

This question is asked many a time in this forum. I know solution for the problem. But I am curious to know why "Enumeration operation can not execute when a collection is modified"

        List<string> list = new List<string>();

        list.Add("a");

        list.Add("b");

        int[] array = new int[6] { 1, 2, 3, 4, 5, 5 };

        HashSet<int> hashSet = new HashSet<int>();

        int i = 0;

        foreach (string s in list)
        {
            list[i] = "test";

            i++;
        }

But when I change list to list.toarray It works.

I am new to C#, sorry if the question does not make any sense.

Thanks,

A: 

When you do list.ToArray() in your foreach, you're making an entire copy of the list contents, and enumerating over the copy. You're no longer making a change to the list while enumerating over the list.

Doing this:

foreach (string s in list.ToArray())
{
   list[i] = "test";
   i++;
}

is effectively the same as doing this:

string[] newArray = list.ToArray();
foreach (string s in newArray)
{
   list[i] = "test";
   i++;
}

Note that, in the second case, you're not enumerating over the collection you are modifying, but rather an entirely new collection.

Reed Copsey
+3  A: 

In general .Net collections do not support being enumerated and modified at the same time. The line list[i] = "test" modifies the collection list while you are in the middel of enumerating it and hence and exception is generated. True this is a trivial modification and doesn't affect the structure of the list but List<T> treats even in place modifications as destructive.

The ToArray version works because now you have 2 collections

  1. list
  2. The created array

You are actually then enumerating the array and hence modifying the original list is just fine.

JaredPar
A: 
supercat