Say I have this block of code in C#:
static void Main(string[] args)
{
List<Func<int>> fs = new List<Func<int>>();
for (int i = 0; i < 5; i++)
fs.Add(() => { return i; });
for (int i = 0; i < 5; i++)
Console.WriteLine(fs[i]());
Console.ReadLine();
}
When I run it, I expected it to print
0
1
2
3
4
but it prints
5
5
5
5
5
instead. My understanding is that the code in Func only keeps an address to i
instead of getting the value of i
, and this approach should be avoided.
So my question is that, is there a way to capture the local variables and pass them into Func
by value?