Nel suo post di ieri, "foreach l'insidioso", Luca si e' chiesto come mai il seguente snippet:
using System.Collections.Generic;
interface IPersistent { }
class Invoice : IPersistent { }
class Order : IPersistent { }
class Program {
    static void Main() {
        List<IPersistent> changedDocuments = new List<IPersistent>();
        changedDocuments.Add(new Invoice());
        changedDocuments.Add(new Order());
        foreach (Invoice changedInvoice in changedDocuments) { }
    }
}
compili. Secondo me, il comportamento del compilatore e' giusto, voluto e documentato. Le specifiche del linguaggio (15.8.4, ECMA-334), dicono:
"A foreach statement of the form
foreach(V v in x) embedded-statement
is then expanded to:
{
    E e = ((C)(x)).GetEnumerator();
    try {
        V v;
        while (e.MoveNext()) {
            v = (V)(T)e.Current;
            embedded-statement
        }
    }
    finally {
        … // Dispose e
    }
}
The variable e is not visible to or accessible to the...