c# · level 3 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
The greeting changes later. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
string greeting = "Hello";
Func<string, string> greet = name => $"{greeting}, {name}!";
greeting = "Welcome back";
Console.WriteLine(greet("Ana"));
your turn
Your turn. Build a discount factory.
Finish the lambda on line 10 so it takes percent off the price. It captures percent from the method around it. Then choose your own percentages on lines 3 and 4.
output
press run to see what happens
fix it
Every table is called at once. Can you fix it?
output
press run to see what happens
- Every table says 4. When do the lambdas run, and what is
iby then? - All three lambdas capture the same
i, and the loop has pushed it to 4 before any of them runs. - Add
int table = i;as the first line inside the loop, print{table}instead of{i}on line 7, then run.
nailed it
your lambdas remember things now. :D
- A lambda captures variables, not copies of their values.
- A closure keeps its variables alive after the method ends.
- Copy a
forvariable inside the loop before capturing it.
new words in your collection
- capture
- closure
This lesson isn’t saved. A free account remembers every lesson you finish.