TExcelTAD
Home › C# › C# Lambdas & Delegates

C# Lambdas & Delegates

In C#, methods can be treated as values: stored in variables, passed as arguments and returned from other methods. The type that makes this possible is the delegate, and the most convenient way to create one is a lambda expression. You have already used lambdas with LINQ (n => n > 5); this lesson explains what is going on underneath.

Delegates

A delegate type describes a method signature — its parameter types and return type. A variable of that type can refer to any method with a matching signature.

csharp · try it yourself
using System;

MathOp op = Add;
Console.WriteLine(op(6, 3));

op = Multiply;
Console.WriteLine(op(6, 3));

Console.WriteLine(Apply(Subtract, 10, 4));

static int Add(int a, int b) => a + b;
static int Multiply(int a, int b) => a * b;
static int Subtract(int a, int b) => a - b;
static int Apply(MathOp operation, int x, int y) => operation(x, y);

delegate int MathOp(int a, int b);
9
18
6

Apply does not know or care which operation it receives — the caller decides. That is the essence of passing behaviour as data.

Func, Action and Predicate

Declaring your own delegate types is rarely necessary. .NET provides generic ones that cover almost every signature:

Delegate Signature Example
Action no parameters, no result Action hello = () => Console.WriteLine("hi");
Action<T1, …> parameters, no result Action<string> log = msg => …;
Func<TResult> no parameters, returns TResult Func<int> dice = () => 4;
Func<T1, …, TResult> parameters, returns the last type argument Func<int, int, int> add = (a, b) => a + b;
Predicate<T> T → bool Predicate<int> isEven = n => n % 2 == 0;

Lambda expressions

A lambda is an anonymous function written as parameters => body. The body can be a single expression or a block in braces.

csharp · try it yourself
using System;

Func<int, int> square = x => x * x;
Func<int, int, int> add = (a, b) => a + b;
Func<string> greet = () => "Hello!";
Action<string> shout = text => Console.WriteLine(text.ToUpper() + "!");
Func<double, double, double> hypotenuse = (a, b) =>
{
    double sum = a * a + b * b;
    return Math.Sqrt(sum);
};

Console.WriteLine(square(9));
Console.WriteLine(add(2, 40));
Console.WriteLine(greet());
shout("lambdas are neat");
Console.WriteLine(hypotenuse(6, 8));
81
42
Hello!
LAMBDAS ARE NEAT!
10

The compiler infers the parameter types from the delegate type. Since C# 10 you can even write var square = (int x) => x * x; and the compiler picks Func<int, int>.

Passing lambdas to methods

The real power comes from methods that accept a function. Here one Filter method handles every kind of condition:

csharp · try it yourself
using System;
using System.Collections.Generic;

static List<T> Filter<T>(IEnumerable<T> items, Func<T, bool> keep)
{
    var result = new List<T>();
    foreach (T item in items)
        if (keep(item)) result.Add(item);
    return result;
}

static void Repeat(int times, Action<int> body)
{
    for (int i = 1; i <= times; i++) body(i);
}

int[] numbers = { 3, 10, 15, 22, 7, 40 };
Console.WriteLine(string.Join(" ", Filter(numbers, n => n > 10)));
Console.WriteLine(string.Join(" ", Filter(numbers, n => n % 5 == 0)));

string[] names = { "Ivy", "Oscar", "Eve", "Bartholomew" };
Console.WriteLine(string.Join(" ", Filter(names, s => s.Length <= 3)));

Repeat(3, i => Console.Write(
quot;[{i}]")); Console.WriteLine();
15 22 40
10 15 40
Ivy Eve
[1][2][3]

This is exactly how LINQ's Where, Select and friends are built.

Closures: capturing variables

A lambda can use variables from the surrounding scope. It captures the variable itself, not a copy of its value, so it sees later changes and can even modify it.

csharp · try it yourself
using System;

int counter = 0;
Action increment = () => counter++;
increment();
increment();
Console.WriteLine(counter);

static Func<int, int> MakeMultiplier(int factor) => x => x * factor;

var triple = MakeMultiplier(3);
var tenTimes = MakeMultiplier(10);
Console.WriteLine(triple(7));
Console.WriteLine(tenTimes(7));

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

var next = MakeCounter();
Console.WriteLine(
quot;{next()} {next()} {next()}");
2
21
70
1 2 3

MakeCounter returns a lambda that keeps its own private count alive even after the method has returned — a closure.

Multicast delegates

A delegate can hold several methods at once. Add with +=, remove with -=; invoking it calls them all in order. This is the foundation of events (next lesson).

csharp · try it yourself
using System;

Action<string> log = msg => Console.WriteLine(
quot;console: {msg}"); log += msg => Console.WriteLine(
quot;file: {msg}"); log += msg => Console.WriteLine(
quot;audit: {msg.Length} chars"); log("User signed in");
console: User signed in
file:    User signed in
audit:   14 chars

Method groups

Where a delegate is expected, you can pass the name of an existing method directly instead of wrapping it in a lambda. numbers.Select(n => Math.Abs(n)) can be written as numbers.Select(Math.Abs), and names.ForEach(n => Console.WriteLine(n)) as names.ForEach(Console.WriteLine).

Tip: Keep lambdas short. If a lambda grows beyond a few lines, give it a name as a regular (or local) method and pass the method group instead.

Test yourself

Which delegate type fits a method that takes a string and returns nothing?

  1. Func<string>
  2. Action<string>
  3. Predicate<string>
  4. Func<string, void>

In Func<int, string, bool>, what is the return type?

  1. int
  2. string
  3. bool
  4. void

What does this print? int x = 1; Func<int> f = () => x * 10; x = 5; Console.WriteLine(f());

  1. 10
  2. 50
  3. 1
  4. 5