I am trying to understand closures, already read some materials but.. then i tried this.
As far as i understand, a class is generated containing the specific anonymous method (in my case, the one writing to the console) and the int variable j. How does it store all the j values in only one class? Are there many instances of this kind of class generated behind the scenes?
class Program { public static List<Action> actions = new List<Action>(); static void Main(string[] args) { AddActions(10); actions[0](); actions[1](); Console.ReadLine(); } public static void AddActions(int count) { for (int i = 0; i < count; i++) { int j = i; actions.Add(delegate() { Console.Write("{0} ", j); }); } } } with result: 0 1