×

c# · level 3 · unit 2 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A lambda can remember the variables around it.

A lambda can use variables from the code around it, not only its own inputs. When it does, it captures them: it keeps hold of the variable itself, not a copy of its value. A lambda that has captured variables is called a .

That makes little factories possible. MakeCounter below creates a local count and hands back a lambda that adds to it. The variable lives on after MakeCounter returns, and each call makes a fresh count, so two counters never share.

Because the variable itself is captured, a change made after the lambda was created still shows up when it runs.

using System;

Func<int> tickets = MakeCounter();
Func<int> raffle = MakeCounter();
tickets();
tickets();
Console.WriteLine(tickets());
Console.WriteLine(raffle());

Func<int> MakeCounter()
{
    int count = 0;
    return () =>
    {
        count++;
        return count;
    };
}

tickets and raffle each captured their own count, so the raffle still starts at 1.