Posts Tagged ‘closures .net java

20
Oct
07

.Net and closures

I’ll try summing up this great article. A sample first:

delegate void  Action();
static void Main(string[] args)
{
    int x = 0;
    Action a = delegate { Console.WriteLine(x); };
    x = 1;
    a();
}

Closures

Here, Action is some anonymous delegate type. Now track what happens to x. Since this is a real closure, what should happen is a() outputting "1", and it does. How does it do it? .Net has no built-in closure support, so through compiler processing, the x object is promoted from the stack to the heap, and a receives a copy of the reference address. This way everyone’s happy.

The Other Side

In Java, there are only ‘half’ closures — these are not as useful as .Net closures. You create inner anonymous classes (Swing’s listeners for example), and every outer variable referenced in it must be final (readonly in .Net). This is essential because Java would copy the value into the inner class, thus no need to handle with heap promotion/stack manipulation.