Cook Computing

Closures and C#

April 6, 2003 Written by Charles Cook

Squawks of the Parrot has some interesting posts on Parrot and virtual machines in general. In C# may do closures now and the following entry Dan questions whether C# supports closures. In one of the comments Sam Ruby points to an article at GotDotNet which describes the new features in a future version of C# including anonymous methods. These seem to be very similar to closures although I don't know enough in this area to say whether there are any subtle differences.

The article contains a paragraph on how anonymous methods are supported:

When an anonymous delegate is encountered, the C# compiler automatically converts the code in its scope of execution into a uniquely named function within a uniquely named class. The delegate in which the code block is stored is then set to reference the compiler-genarated object and method. When the delegate is invoked, the anonymous method block is executed via the compiler-generated method.

almostperfect points to a comment by Miguel Icaza (on an earlier Squawks entry) which mentions that no changes are required to the virtual machine and provides some code illustrations as to how this implementation of anonymous methods works. It reminds me of function objects in C++.

Jon Shute thinks that anonymous methods will make testing more difficult which may be true but I disagree with his point that the new feature only saves one line of code: if you are capturing a lot of state in the anonymous method (any of the class members, current method parameters, or local variables, i.e. potentially anything within scope where the anonymous method is defined) then you could be avoiding a lot of extra code.