Skip to content

Delegates and Lambdas

The Course
•
30 min study

So far, methods have received data. A delegate lets a method receive behaviour: a value that represents a method you can call later. Today's work on LINQ relies on this idea on nearly every line.

Func and Action

Func<int, int> is "a method that takes an int and returns an int". The last type argument is the return type. Action<string> is "a method that takes a string and returns nothing". You can store a method in a variable of that type.

A method in a variable C#
Func<int, int> change = Double;
Console.WriteLine(change(5));

change = Negate;
Console.WriteLine(change(5));

Action<string> show = Console.WriteLine;
show("shown");

static int Double(int x) => x * 2;
static int Negate(int x) => -x;
Check your prediction
Text
10
-5
shown

Double has no parentheses there, because you aren't calling it. You're referring to it.

Lambdas

A lambda is a method without a name, written where it's used. To the left of => are the parameters, and to the right is the body. Passing behaviour to a method makes that method far more reusable.

Passing a test to a method C#
int[] numbers = { 1, 2, 3, 4, 5, 6 };

Console.WriteLine(CountWhere(numbers, n => n % 2 == 0));
Console.WriteLine(CountWhere(numbers, n => n > 4));
Console.WriteLine(CountWhere(numbers, n =>
{
    int square = n * n;
    return square < 10;
}));

static int CountWhere(IEnumerable<int> values, Func<int, bool> test)
{
    int count = 0;
    foreach (int value in values)
    {
        if (test(value))
        {
            count++;
        }
    }
    return count;
}
Check your prediction
Text
3
2
3

Closures: lambdas remember

A lambda can use variables from the code around it. It captures the variable itself, not a copy of its value, so later changes are visible. Predict carefully.

The lambda sees the change C#
int limit = 3;
Func<int, bool> small = n => n < limit;

Console.WriteLine(small(5));
limit = 10;
Console.WriteLine(small(5));

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

static Func<int> MakeCounter()
{
    int count = 0;
    return () => ++count;
}
Check your prediction
Text
False
True
2

count outlives MakeCounter, because the returned lambda still needs it. That's powerful, and it's also a source of bugs when a captured variable changes unexpectedly. Prefer capturing things that stay the same.

Generic and returning functions

Generics and delegates combine well. Map below works for any input and output types, and the compiler works out TIn and TOut. Twice even takes a function and returns a new one.

Generic behaviour C#
foreach (int length in Map(new[] { "a", "bcd" }, word => word.Length))
{
    Console.WriteLine(length);
}

Func<int, int> addTwo = Twice((int n) => n + 1);
Console.WriteLine(addTwo(10));

static IEnumerable<TOut> Map<TIn, TOut>(IEnumerable<TIn> items, Func<TIn, TOut> change)
{
    foreach (TIn item in items)
    {
        yield return change(item);
    }
}

static Func<T, T> Twice<T>(Func<T, T> step) => value => step(step(value));
Check your prediction
Text
1
3
12

Fix it: Three lambdas, one variable

Each lambda should print the number it was made with. Predict the output, then run it.

Three lambdas, one variable C#
var actions = new List<Action>();
for (int i = 0; i < 3; i++)
{
    actions.Add(() => Console.WriteLine(i));
}

foreach (Action action in actions)
{
    action();
}
Check your prediction
Text
3
3
3

A lambda captures the variable, not its value at that moment, and a for loop has one i that all three lambdas share. By the time they run, the loop has finished and i is 3. Fix it so that it prints 0, 1 and 2.

Fix it

Copy the value into a variable declared inside the loop body. Each pass of the loop gets a new copy, so each lambda captures its own:

C#
var actions = new List<Action>();
for (int i = 0; i < 3; i++)
{
    int copy = i;
    actions.Add(() => Console.WriteLine(copy));
}

foreach (Action action in actions)
{
    action();
}
Text
0
1
2

A foreach variable is new on each pass, so foreach (int n in numbers) doesn't have this problem. It's the for loop, and any variable declared outside the loop, that's shared.

Your turn

Exercise

A small retry helper

Write Retry<T>(Func<T> action, int attempts). It calls action until it succeeds, returning the result. If action throws, and attempts remain, it tries again. When the last attempt throws, that exception should reach the caller.

Test it with a lambda that throws InvalidOperationException the first two times and then returns "worked", using a captured counter. Print the result and the number of calls. Then call it with only one attempt on a lambda that always throws, and print gave up when you catch the exception.

When it works, it prints:

Text
worked
3
gave up
Your workspace C#
Console.WriteLine("Start here");
Hint 1: the idea

Every attempt except the last may fail quietly and lead to another try. The last one is different: nothing should catch its exception. So the last attempt doesn't need to be inside the loop at all.

Hint 2: a first step

Write a for loop that runs attempts - 1 times, with return action(); inside a try and an empty catch. Test it with the counting lambda and 5 attempts: you should see worked and 3. Then decide what goes after the loop.

Show one solution
C#
int calls = 0;
string result = Retry(() =>
{
    calls++;
    if (calls < 3)
    {
        throw new InvalidOperationException("not yet");
    }
    return "worked";
}, 5);
Console.WriteLine(result);
Console.WriteLine(calls);

try
{
    Retry<int>(() => throw new InvalidOperationException("never"), 1);
}
catch (InvalidOperationException)
{
    Console.WriteLine("gave up");
}

static T Retry<T>(Func<T> action, int attempts)
{
    for (int attempt = 1; attempt < attempts; attempt++)
    {
        try
        {
            return action();
        }
        catch (Exception)
        {
            // Not the last attempt, so try again.
        }
    }
    return action();
}
Text
worked
3
gave up

The loop gives every attempt but the last a try, and the final return action(); sits outside it, so whatever the last attempt throws reaches the caller unchanged, with no extra code. A success on any attempt returns straight out of the loop. With attempts set to 1 the loop body never runs, and the single call is the last attempt, which is exactly the "gave up" case.

Catching every Exception is reasonable only in a helper like this, which is about retrying. On Day 4 you'll meet two other ways to write it: a catch with a when filter, which only catches while attempts remain, and throw;, which passes on the exception you caught.

Was this article helpful?

Your response is saved on this device.