What are 'closures' in .NET?

Developer picture Developer · Jan 9, 2009 · Viewed 40.6k times · Source

What is a closure? Do we have them in .NET?

If they do exist in .NET, could you please provide a code snippet (preferably in C#) explaining it?

Answer

Jon Skeet picture Jon Skeet · Jan 9, 2009

I have an article on this very topic. (It has lots of examples.)

In essence, a closure is a block of code which can be executed at a later time, but which maintains the environment in which it was first created - i.e. it can still use the local variables etc of the method which created it, even after that method has finished executing.

The general feature of closures is implemented in C# by anonymous methods and lambda expressions.

Here's an example using an anonymous method:

using System;

class Test
{
    static void Main()
    {
        Action action = CreateAction();
        action();
        action();
    }

    static Action CreateAction()
    {
        int counter = 0;
        return delegate
        {
            // Yes, it could be done in one statement; 
            // but it is clearer like this.
            counter++;
            Console.WriteLine("counter={0}", counter);
        };
    }
}

Output:

counter=1
counter=2

Here we can see that the action returned by CreateAction still has access to the counter variable, and can indeed increment it, even though CreateAction itself has finished.