I was just curious about this: the following code will not compile, because we cannot modify a foreach iteration variable:
foreach (var item in MyObj
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() one. 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.