Why can't we assign a foreach iteration variable, whereas we can completely modify it with an accessor?

I was just curious about this: the following code will not compile, because we cannot modify a foreach iteration variable:

        foreach (var item in MyObjectList)
        {
            item = Value;
        }

But the following will compile and run:

        foreach (var item in MyObjectList)
        {
            item.Value = Value;
        }

Why is the first invalid, whereas the second can do the same underneath (I was searching for the correct english expression for this, but I don't remember it. Under the...? ^^ )


foreach is a read only iterator that iterates dynamically classes that implement IEnumerable, each cycle in foreach will call the IEnumerable to get the next item, the item you have is a read only reference, you can not re-assign it, but simply calling item.Value is accessing it and assigning some value to a read/write attribute yet still the reference of item a read only reference.


The second isn't doing the same thing at all. It's not changing the value of the item variable - it's changing a property of the object to which that value refers. These two would only be equivalent if item is a mutable value type - in which case you should change that anyway, as mutable value types are evil. (They behave in all kinds of ways which the unwary developer may not expect.)

It's the same as this:

private readonly StringBuilder builder = new StringBuilder();

// Later...
builder = null; // Not allowed - you can't change the *variable*

// Allowed - changes the contents of the *object* to which the value
// of builder refers.
builder.Append("Foo");

See my article on references and values for more information.


You can't modify a collection while it's being enumerated. The second example only updates a property of the object, which is entirely different.

Use a for loop if you need to add/remove/modify elements in a collection:

for (int i = 0; i < MyObjectList.Count; i++)
{
    MyObjectList[i] = new MyObject();
}

If you look at the language specification you can see why this is not working:

The specs say that a foreach is expanded to the following code:

 E e = ((C)(x)).GetEnumerator();
   try {
      V v;
      while (e.MoveNext()) {
         v = (V)(T)e.Current;
                  embedded-statement
      }
   }
   finally {
      … // Dispose e
   }

As you can see the current element is used to call MoveNext() on. So if you change the current element the code is 'lost' and can't iterate over the collection. So changing the element to something else doesn't make any sense if you see what code the compiler is actually producing.