Apologies if this question has been asked already, but suppose we have this code (I've run it with Mono 2.10.2 and compiled with gmcs
2.10.2.0):
using System;
public class App {
public static void Main(string[] args) {
Func<string> f = null;
var strs = new string[]{
"foo",
"bar",
"zar"
};
foreach (var str in strs) {
if ("foo".Equals(str))
f = () => str;
}
Console.WriteLine(f()); // [1]: Prints 'zar'
foreach (var str in strs) {
var localStr = str;
if ("foo".Equals(str))
f = () => localStr;
}
Console.WriteLine(f()); // [2]: Prints 'foo'
{ int i = 0;
for (string str; i < strs.Length; ++i) {
str = strs[i];
if ("foo".Equals(str))
f = () => str;
}}
Console.WriteLine(f()); // [3]: Prints 'zar'
}
}
It seems logical that [1]
print the same as [3]
. But to be honest, I somehow expected it to print the same as [2]
. I somehow believed the implementation of [1]
would be closer to [2]
.
Question: Could anyone please provide a reference to the specification where it tells exactly how the str
variable (or perhaps even the iterator) is captured by the lambda in [1]
.
I guess what I am looking for is the exact implementation of the foreach
loop.