Understanding Variable Capturing in C#

With the addition of anonymous delegates in C# 2.0 and with lambda expressions in C# 3.0 you might have been hearing a lot about variable capturing.  This is the mechanism in which the delegate/lambda which was defined inline is able to hold on to any variables within its lexical scope. 

For example in this code:

static void Main(string[] args)
{
    Console.WriteLine("Variable Capturing");
 
    string name = "Matthew";
    Func<String> capture = () => name;
 
    name = "Mallory";
 
    Print(capture);
 
}
 
static void Print(Func<string> capture)
{
    Console.WriteLine(capture());
}

A new class was created called “Capture”.  All occurrence of the variable “name” in the original code have been replaced by a field access to the “name” member of the capture class.  Also, the lambda expression becomes just a method on the capture class which I called Lambda (yep, that is all anonymous delegates and lambda expression really are).  This is how changes in the variable get persisted in the lambda expression, every change to the variable just modifies the field in the Capture class.

That is all there is to it, simple!