Lambdas and delegates
A delegate is a type
A delegate names a method signature. A variable of a delegate type holds a method with that signature, and calling the variable calls the method. C# declares two families for the common shapes: Func<...> returns a value and Action<...> returns nothing, each with up to sixteen parameters.
Func<int, int> square = n => n * n;
Console.WriteLine(square(4));
Action<string> log = message => Console.WriteLine($"log: {message}");
log("started");
Predicate<int> isEven = n => n % 2 == 0;
Console.WriteLine(isEven(10));
Console.WriteLine(Apply(5, square));
Console.WriteLine(Apply(5, n => n + 1));
static int Apply(int value, Func<int, int> operation) => operation(value);
dotnet run
16
log: started
True
25
6
Five lines, and each shows a part. square is a
Func<int, int>. log
is an Action<string>, the delegate of a method
that returns nothing. isEven is a
Predicate<int>, the same shape as
Func<int, bool>.
Apply takes a delegate as a parameter, so the same
method computes a square and a successor.
A delegate is an object: it holds a target and a method. That is why a
lambda assigned to a variable allocates once and calling it afterwards
allocates nothing.
Lambdas and Func
A lambda is the body of a method without a name and without a declaration: n => n * n is one parameter and one expression, (a, b) => a + b is two, and a block body goes in braces. A lambda that takes no parameters is () => ....
Func<int, int, int> add = (a, b) => a + b;
Action nothing = () => Console.WriteLine("nothing to report");
Func<string> greet = () =>
{
var hour = 9;
return hour < 12 ? "good morning" : "good day";
};
Console.WriteLine(add(2, 3));
nothing();
Console.WriteLine(greet());
dotnet run
5
nothing to report
good morning
The type of a lambda is a delegate type, and it is chosen by the context: a lambda assigned to a Func<int, int, int> takes two ints and returns an int. The same text in another context would be another delegate, which is why a lambda cannot be written without a type the compiler can infer from somewhere — an assignment, an argument or a cast.
The capture
A lambda that reads a local variable captures it, exactly as a local function does, and it captures the variable rather than its value:
int factor = 3;
Func<int, int> times = n => n * factor;
factor = 10;
Console.WriteLine(times(2));
dotnet run
20
The 20 is the proof: the lambda used the value 10, the one the variable held when the call happened, not the 3 it held when the lambda was written. In a loop that captures the loop variable, every lambda therefore sees the last value, and the fix is a local copy inside the loop or, since C# 5, a foreach variable that is already per-iteration.
A method group
A method name without parentheses is a method group: the compiler turns it into a delegate when the target type is known.
Func<int, int> twice = Double;
Console.WriteLine(twice(5));
static int Double(int n) => n * 2;
dotnet run
10
This form is shorter than a lambda and, unlike a capturing lambda, allocates nothing per call: the delegate can point at the method itself. An overloaded method makes the group ambiguous until the target type chooses the overload, which is one more reason the delegate type is written explicitly.
Exercises
- Write Func<int, bool> as a filter and pass it to a method that returns the matching numbers of an array.
- Capture a loop variable in a lambda inside a for loop and print what the lambda sees after the loop. Why is it the last value?
- Turn the Double method group into a lambda. Which version allocates?
- Write a delegate type of your own with delegate int Op(int a, int b); and assign both a lambda and a named method to it.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a delegate variable hold?
Answer
A method with a matching signature, which the variable can call
A delegate is an object with a target and a method, and invoking the variable invokes that method.
-
Which delegate returns nothing?
Answer
Action
Action is the void family; Func returns a value and Predicate returns a bool.
-
What does this program print?
Func<int, int> square = n => n * n; Console.WriteLine(square(5));Answer
25
The lambda takes one int and returns its square, so the call gives 25.
-
What does this program print?
int factor = 3; Func<int, int> times = n => n * factor; factor = 10; Console.WriteLine(times(2));Answer
20
The lambda captures the variable, so it reads the value at the moment of the call, which is 10.
-
What is a method group?
Answer
A method name without a call, converted to a delegate when the type is known
Writing Double where a Func<int, int> is expected makes a delegate that points at the method.
-
What does this program print?
Action<string> log = message => Console.WriteLine($"log: {message}"); log("started");Answer
log: started
The lambda takes the string and prints it inside the prefix, and an Action returns nothing.
-
Why can a lambda not be assigned to var on its own?
Answer
A lambda has no type of its own; the delegate type must come from the context
The compiler converts a lambda to a delegate or an expression tree, and it needs to know which one.
-
What does this program print?
Func<int, int> twice = Double; Console.WriteLine(twice(4)); static int Double(int n) => n * 2;Answer
8
The method group becomes a delegate to Double, and the call returns 8.
-
Which lambda takes two parameters and returns their sum?
Answer
(a, b) => a + b
Two parameters go in parentheses, and the expression after => is the result.
-
What does a delegate parameter let a method do?
Answer
Take a piece of behaviour from the caller, as Apply does
The delegate is a parameter whose value is a method, which is what lets one method serve several operations.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev