In C#, why can’t I modify the member of a value type instance in a foreach loop?

Because foreach uses an enumerator, and enumerators can’t change the underlying collection, but can, however, change any objects referenced by an object in the collection. This is where Value and Reference-type semantics come into play.

On a reference type, that is, a class, all the collection is storing is a reference to an object. As such, it never actually touches any of the object’s members, and couldn’t care less about them. A change to the object won’t touch the collection.

On the other hand, value types store their entire structure in the collection. You can’t touch its members without changing the collection and invalidating the enumerator.

Moreover, the enumerator returns a copy of the value in the collection. In a ref-type, this means nothing. A copy of a reference will be the same reference, and you can change the referenced object in any way you want with the changes spreading out of scope. On a value-type, on the other hand, means all you get is a copy of the object, and thus any changes on said copy will never propagate.

Leave a Comment