There's no general way to do this - but if you're only bothered by the specific issue of foreach
, then there are two options:
- Start using a C# 5 compiler (you don't need to target .NET 4.5 or anything like that). The rules around captured
foreach
iteration variables changed (to sane ones) for C# 5. If you're stuck with C# 3 or 4, capture a local variable declared in the loop:
foreach(String s in strings) { string copy = s; result.Add(() => Console.WriteLine(copy)); }
That way each iteration of the loop captures a separate variable, which never changes value.