Example of Surprising Closure Behavior

::: {style="font-size: 10pt; background: white; color: black; font-family: courier new"} What do you expect to be outputted from this program (note that line 19 captures the outer variable "i")?

[    1]{style="color: #2b91af"} [using]{style="color: blue"} System;

[    2]{style="color: #2b91af"} [using]{style="color: blue"} System.Collections.Generic;

[    3]{style="color: #2b91af"} [using]{style="color: blue"} System.Text;

[    4]{style="color: #2b91af"} [using]{style="color: blue"} System.Threading;

[    5]{style="color: #2b91af"} 

[    6]{style="color: #2b91af"} [delegate]{style="color: blue"} [void]{style="color: blue"} [VoidDelegate]{style="color: teal"}();

[    7]{style="color: #2b91af"} 

[    8]{style="color: #2b91af"} [class]{style="color: blue"} [Program]{style="color: teal"}

[    9]{style="color: #2b91af"} {

[   10]{style="color: #2b91af"}     [public]{style="color: blue"} [static]{style="color: blue"} [void]{style="color: blue"} Main([string]{style="color: blue"}[] args)

[   11]{style="color: #2b91af"}     {

[   12]{style="color: #2b91af"}         [List]{style="color: teal"}\<[VoidDelegate]{style="color: teal"}> closures = [new]{style="color: blue"} [List]{style="color: teal"}\<[VoidDelegate]{style="color: teal"}>();

[   13]{style="color: #2b91af"}         [//Create a bunch of closures]{style="color: green"}

[   14]{style="color: #2b91af"}         [for]{style="color: blue"} ([int]{style="color: blue"} i = 0; i \< 10; i++)

[   15]{style="color: #2b91af"}         {

[   16]{style="color: #2b91af"}             [VoidDelegate]{style="color: teal"} myClosure = [delegate]{style="color: blue"}

[   17]{style="color: #2b91af"}             {

[   18]{style="color: #2b91af"}                 [//Capture outer variable]{style="color: green"}

[   19]{style="color: #2b91af"}                 [Console]{style="color: teal"}.WriteLine(i);

[   20]{style="color: #2b91af"}             };

[   21]{style="color: #2b91af"}             closures.Add(myClosure);

[   22]{style="color: #2b91af"}         }

[   23]{style="color: #2b91af"} 

[   24]{style="color: #2b91af"}         [foreach]{style="color: blue"} ([VoidDelegate]{style="color: teal"} closure [in]{style="color: blue"} closures)

[   25]{style="color: #2b91af"}         {

[   26]{style="color: #2b91af"}             closure();

[   27]{style="color: #2b91af"}         }

[   28]{style="color: #2b91af"}         [Console]{style="color: teal"}.ReadKey();

[   29]{style="color: #2b91af"}     }

[   30]{style="color: #2b91af"} }

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()
} :::

blogroll

social