CSharp - Lambda Outer Variables Capturing

Introduction

A lambda expression can reference the local variables and method parameters.

Outer variables referenced by a lambda expression are called captured variables.

A lambda expression that captures variables is called a closure.

For example:

static void Main()
{
       int factor = 2;
       Func<int, int> multiplier = n => n * factor;
       Console.WriteLine (multiplier (3));
}

Captured variables are evaluated when the delegate is invoked.

int factor = 2;

Func<int, int> multiplier = n => n * factor;
factor = 10;
Console.WriteLine (multiplier (3));

Lambda expressions can update captured variables:

int seed = 0;
Func<int> natural = () => seed++;
Console.WriteLine (natural());           // 0
Console.WriteLine (natural());           // 1
Console.WriteLine (seed);                // 2

The following code returns a Lambda expressions with captured variable.

using System;
class MainClass
{
   public static void Main(string[] args)
   {
       Func<int> natural = Natural();
       Console.WriteLine (natural());      // 0
       Console.WriteLine (natural());      // 1
   }
   static Func<int> Natural()
   {
       int seed = 0;
       return () => seed++;      // Returns a closure
   }

}

A local variable within a lambda expression is unique per invocation of the delegate instance.

using System;
class MainClass
{
   public static void Main(string[] args)
   {
       Func<int> natural = Natural();
       Console.WriteLine (natural());           // 0
       Console.WriteLine (natural());           // 0
   }
    static Func<int> Natural()
    {
           return() => { int seed = 0; return seed++; };
    }

}

Related Topics