Closures: Lambdas That Remember

A lambda can use the local variables around it. It captures the variable itself, not a copy of its value, and keeps it alive for as long as the lambda lives, which is how a method can hand back a counter that remembers its count.

Journeyman · C# · Updated

By

After this lesson you can

  • Write a lambda that uses a local variable from the code around it, and predict what it sees when that variable changes
  • Write a method that returns a lambda which keeps its own captured variable, such as a counter

Key takeaways

  • A lambda can use a local variable from the code around it, such as the budget in price => price <= budget. A lambda together with the variables it uses is called a closure.
  • A lambda captures the variable itself, not a copy of its value, so a change made after the lambda was written is a change the lambda sees.
  • A method can return a lambda that uses one of the method's local variables. That variable lives on after the method returns, and only the lambda can reach it.
  • Each call to such a method makes a brand-new variable, so two counters made by two calls count separately.
  • A for loop has one loop variable for all its passes, so lambdas made inside it all see its last value. Copy it into a local variable inside the loop; foreach makes a fresh one each pass.

An online store shows only the products a shopper can afford. The shopper types a budget, and the page lists every price at or under it. You know how to filter with a lambda, but this lambda needs something its parameter doesn't give it: the budget, which nobody knows until the shopper types it.

You'll meet this whenever a lambda needs a value from outside: the text in a search box, a shopper's budget, a setting someone picked. This lesson shows how a lambda gets hold of such a value, and the one trap that catches almost everyone the first time.

A lambda that needs one more value

Here are the store's prices. With a budget of $20, the filter you already know does the job:

List<decimal> prices = new List<decimal> { 4.99m, 12.50m, 18.00m, 24.95m, 39.99m };

List<decimal> affordable = prices.Where(price => price <= 20.00m).ToList();

But 20.00m is written into the code, so every shopper gets a $20 budget. The next shopper has $30. And you can't ask Where to pass the budget in as a second parameter: Where hands your lambda one price at a time, and it knows nothing about budgets.

The way out is that a lambda can use a local variable from the code around it, a variable declared in the same method, not only its own parameters:

List<decimal> prices = new List<decimal> { 4.99m, 12.50m, 18.00m, 24.95m, 39.99m };
decimal budget = 20.00m;

List<decimal> affordable = prices.Where(price => price <= budget).ToList();

Console.WriteLine(string.Join(", ", affordable));
4.99, 12.50, 18.00

Read the lambda aloud: price such that price is at most budget. price is its parameter, but budget isn't: the lambda reaches out to the code around it and uses that variable. In a real store, budget would come from what the shopper typed, and the same line would work for every shopper.

We say the lambda captures budget. A lambda together with the variables it captures is called a closure: it closes over them and takes them along, the way a lunchbox closes over the lunch inside it.

It captures the variable, not its value

Think of the difference between a photo of a scoreboard and a window that looks out at it. A photo shows the score when it was taken. A window shows the score now. A captured variable is a window: the lambda doesn't keep a copy of budget's value from when it was written, it keeps the variable itself, and reads whatever is in it each time it runs.

decimal budget = 20.00m;
Func<decimal, bool> canAfford = price => price <= budget;

Console.WriteLine(canAfford(24.95m));

budget = 30.00m;
Console.WriteLine(canAfford(24.95m));
False
True

The lambda was written when budget was 20, but the second call runs after the shopper raised it to 30, so the lambda sees 30. (Func<decimal, bool> is a lambda that takes a decimal and returns a bool, as in Lambda Expressions.)

A window works in both directions: a lambda can also change a captured variable. An Action with nothing in its angle brackets takes nothing and returns nothing, and () is how a lambda with no parameters is written:

int itemsScanned = 0;
Action scan = () => itemsScanned++;

scan();
scan();
scan();

Console.WriteLine(itemsScanned);
3

Each call to scan adds 1 to the same itemsScanned the rest of the code sees.

A method that hands back a lambda

A museum counts its visitors with a hand clicker at each door. Each click adds 1 and shows the new total. The count has to survive between clicks, but nothing else should be able to change it.

A local variable usually can't help here. Its scope is the method it's declared in: when the method returns, the variable is gone, and the next call starts over. A closure changes that. A method can return a lambda, and if that lambda captured one of the method's local variables, the variable stays alive for as long as the lambda does:

Func<int> frontDoor = MakeCounter();

Console.WriteLine(frontDoor());
Console.WriteLine(frontDoor());
Console.WriteLine(frontDoor());

Func<int> MakeCounter()
{
    int count = 0;
    return () =>
    {
        count++;
        return count;
    };
}
1
2
3
  • Func<int> is a lambda that takes nothing and returns an int. That's the clicker: call it, and it gives the new count.
  • MakeCounter runs once. It makes count, and returns a lambda that adds 1 to count and returns it. Then MakeCounter is finished.
  • count would normally be gone now, but the lambda captured it, so C# keeps it alive. Each call to frontDoor() changes that same count.
  • No other code can reach count: there's no name for it outside the lambda. It's as private as a private field in a class.

Each call makes a new variable

The side door needs a clicker too, with a count of its own:

Func<int> frontDoor = MakeCounter();
Func<int> sideDoor = MakeCounter();

frontDoor();
frontDoor();
Console.WriteLine(frontDoor());
Console.WriteLine(sideDoor());

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

Each call to MakeCounter runs int count = 0; again, which makes a brand-new count. The front door's lambda captured the first one, and the side door's lambda captured the second. It works like new and a class: every object made with new gets fields of its own.

The loop trap

A café builds one announcement for each of its three tables, in a loop, to call out later when each order is ready:

List<Func<string>> callouts = new List<Func<string>>();

for (int table = 1; table <= 3; table++)
{
    callouts.Add(() => quot;Table {table}, your order is ready");
}

foreach (Func<string> callout in callouts)
{
    Console.WriteLine(callout());
}
Table 4, your order is ready
Table 4, your order is ready
Table 4, your order is ready

Table 4 doesn't even exist. Here's why. A for loop has one variable, table, for all of its passes; each pass changes its value. All three lambdas captured that same variable, not its value at the time. The loop stops when table becomes 4 (that's when table <= 3 is false), and the lambdas only run after that, so all three read 4.

On the left, a for loop: three lambdas all point at one shared table variable, which holds 4 once the loop ends, so each says Table 4. On the right, the fix: each pass copies table into its own thisTable variable, holding 1, 2 and 3, and each lambda points at its own

The fix is to give each lambda a variable of its own. A variable declared inside the loop's braces is a new variable on every pass, so copy the loop variable into one and capture the copy:

List<Func<string>> callouts = new List<Func<string>>();

for (int table = 1; table <= 3; table++)
{
    int thisTable = table;
    callouts.Add(() => quot;Table {thisTable}, your order is ready");
}

foreach (Func<string> callout in callouts)
{
    Console.WriteLine(callout());
}
Table 1, your order is ready
Table 2, your order is ready
Table 3, your order is ready

A foreach loop doesn't have the trap: it makes a fresh loop variable for each pass, so foreach (int table in tables) with List<int> tables = new List<int> { 1, 2, 3 }; gives each lambda its own table, and they print 1, 2 and 3.

Do it: give each child a savings jar

A family's app gives each child a savings jar. A jar starts with some money in it. Each time money goes in, the jar adds it and shows the new balance. Every child's jar keeps its own money.

The method gets one value:

  • startingBalance: the money already in the jar, a decimal (10.00m). It's never below 0.

It returns the jar: a Func<decimal, decimal>. Call the jar with a deposit, the money going in (a decimal, never below 0), and it returns the jar's balance after that deposit.

For example, Maya's jar starts with $10.00, then she puts in $5.00 and then $2.50:

Func<decimal, decimal> mayasJar = MakeSavingsJar(10.00m);
mayasJar(5.00m);
mayasJar(2.50m);
Call Balance before Deposit Returns
mayasJar(5.00m) 10.00 5.00 15.00m
mayasJar(2.50m) 15.00 2.50 17.50m

So the first call returns 15.00m and the second returns 17.50m.

Your job: write the method Func<decimal, decimal> MakeSavingsJar(decimal startingBalance) so it returns a jar.

  • Each call to the jar adds the deposit to the jar's balance and returns the new balance.
  • Each jar keeps its own balance: two jars made by two calls to MakeSavingsJar never share money.
  • A deposit of 0m leaves the balance as it was, and returns it.

Practiced live on the lesson page: write the C# right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

A closure lets a lambda carry what it needs, a budget, a count, a balance, wherever it goes. Remember that it holds the variable, not a snapshot of it, and copy a for loop's variable before a lambda captures it.

Key terms

Cheat sheets