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.
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
10
-5
shownDouble 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.
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
3
2
3Closures: 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.
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
False
True
2count 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.
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
1
3
12Fix it: Three lambdas, one variable
Each lambda should print the number it was made with. Predict the output, then run it.
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
3
3
3A 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:
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();
}0
1
2A 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
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:
worked
3
gave upConsole.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
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();
}worked
3
gave upThe 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.
Completion is saved in this browser only. It does not measure mastery.