Software development industry analysis by Larry O'Brien, the former editor of Software Development and Computer Language
Sunday, August 20, 2006

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

Sunday, August 20, 2006 9:59:15 AM (Hawaiian Standard Time, UTC-10:00) |  Disqus link  | Knowing | C# | Ruby#
Tracked by:
"Java May Get Closures: Functional Programming on the March!" (Knowing.NET) [Trackback]
http://www.knowing.net/PermaLink,guid,7c0b023e-5aff-45ad-b013-e2ae64b39ca1.aspx [Pingback]
Search
About Larry...
Flickr photostream
Subscribe: RSS 2.0 Atom 1.0
Popular Articles
Programming Sabre with Java, C#, and XML
Genetic Programming in C#
15 Exercises To Know A Programming Language
Top 10 Things I've Learned About Computers From the Movies and Any Episode of "24"
Recently Published Articles
HI
KonaKoder
Categories
Archive
Admin Login
Sign In
Toolroll