c# - Lambda variable capture in loop - what happens here? -
i trying head around, happens here ? sort of code compiler produce?
public static void vc() { var listactions = new list<action>(); foreach (int in enumerable.range(1, 10)) { listactions.add(() => console.writeline(i)); } foreach (action action in listactions) { action(); } } static void main(string[] args) { vc(); } output: 10 10 .. 10
according this, new instance of actionhelper created every iteration. in case, assume should print 1..10. can give me pseudo code of compiler doing here ?
thanks.
in line
listactions.add(() => console.writeline(i)); the variable i, captured, or if wish, created pointer memory location of variable. means every delegate got pointer memory location. after loop execution:
foreach (int in enumerable.range(1, 10)) { listactions.add(() => console.writeline(i)); } for obvious reasons i 10, memory content pointers present in action(s) pointing, becomes 10.
in other words, i captured.
by way, should note, according eric lippert, "strange" behaviour resolved in c# 5.0.
so in c# 5.0 program print as expected:
1,2,3,4,5...10 edit:
can not find eric lippert's post on subject, here one: