Why can’t I modify the loop variable in a foreach?

I’m not sure exactly what you mean by a “readonly loop” but I’m guessing that you want to know why this doesn’t compile:

int[] ints = { 1, 2, 3 };
foreach (int x in ints)
{
    x = 4;
}

The above code will give the following compile error:

Cannot assign to 'x' because it is a 'foreach iteration variable'

Why is this disallowed? Trying to assigning to it probably wouldn’t do what you want – it wouldn’t modify the contents of the original collection. This is because the variable x is not a reference to the elements in the list – it is a copy. To avoid people writing buggy code, the compiler disallows this.

Leave a Comment