Saturday, February 15, 2014

closure

Source: http://www.codethinked.com/c-closures-explained


Closure is one of those techniques you’ve probably used (if you write much code), but may not have known the name. In short, closure is when an inner function captures its parent’s variables. Closure is supported by JavaScript, C#, PHP and probably more languages. Following is one of the best examples I’ve found (in C#).















static void Main(string[] args)
{
    var inc = GetAFunc();
    Console.WriteLine(inc(5));
    Console.WriteLine(inc(6));
}

public static Func<int,int> GetAFunc()
{
    var myVar = 1;
    Func<int, int> inc = delegate(int var1)
                         {
                            myVar = myVar + 1;
                            return var1 + myVar;
                         };
    return inc;
}

Hmmm, stare at that for just a second. When we call "GetAFunc", we get a method back that increments a local variable inside of the method. You see? "myVar" is a local variable, but when we return the "inc" method, it is bound inside of the delegate.
But don’t local variables get created on the stack? Don’t they go away when we finish executing the method? Normally yes. But if we ran this code, this would be the result:
7
9
So, when we passed back the method, the variable now lives along with the method. Outside of its original scope. You see, it got incremented when we called the method twice. Crazy!

But you know what is even more crazy? You just learned what a closure is! You just bound some free variables in the lexical environment! Don’t you just feel super smart now?

You see, it is oh so simple. It is really all about variables getting referenced which might leave scope. So you can say that these delegates are "closed" over these variables, which causes them to live outside of their lexical scope.

No comments:

Post a Comment