What do you expect to be outputted from this program (note that line 19 captures the outer variable "i")?
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Threading;
5
6 delegate void VoidDelegate();
7
8 class Program
9 {
10 public static void Main(string[] args)
11 {
12 List<VoidDelegate> closures = new List<VoidDelegate>();
13 //Create a bunch of closures
14 for (int i = 0; i < 10; i++)
15 {
16 VoidDelegate myClosure = delegate
17 {
18 //Capture outer variable
19 Console.WriteLine(i);
20 };
21 closures.Add(myClosure);
22 }
23
24 foreach (VoidDelegate closure in closures)
25 {
26 closure();
27 }
28 Console.ReadKey();
29 }
30 }
Contrast with the output of this Ruby program:
closures = Array.new()
#Create a bunch of closures
10.times { | i |
myClosure = lambda {
#Capture outer variable
puts(i)
}
closures.push(myClosure)
}
closures.each { | myClosure |
myClosure.call()
}