Tutorials / Advanced C# and .NET / Delegates, events and lambdas

Delegates, events and lambdas

15 min read csharp
Course contents (16 lessons)
  1. The type system
  2. Records, structs and value equality
  3. Interfaces and abstract classes
  4. Generics and constraints
  5. Delegates, events and lambdas
  6. Querying and matching data
  7. LINQ in depth: deferred execution, grouping and joins
  8. IEnumerable versus IQueryable
  9. Pattern matching in modern C#
  10. Async and await: how Task really works
  11. Async patterns: cancellation, timeouts and async streams
  12. Application structure
  13. Dependency injection and service lifetimes
  14. Configuration, options and logging
  15. Data and web
  16. Entity Framework Core basics: DbContext, migrations and queries
  17. Building a minimal API with ASP.NET Core
  18. Unit testing with xunit
  19. Performance and the final project
  20. Performance basics: Span of T and fewer allocations
  21. Final project: a notes API with EF Core, DI and logging

Passing behaviour around

Usually you pass data to a method. Sometimes you want to pass an action: "run this code when the download finishes" or "sort using this rule". In C# a delegate is a type that represents a method. You can store it in a variable, pass it as an argument and call it later.

You rarely declare your own delegate type now. .NET gives three ready-made families:

  • Action is a method that returns nothing, with up to 16 parameters. Action<string> takes a string.
  • Func returns a value. The last type argument is the return type. Func<int, int, int> takes two ints and returns an int.
  • Predicate<T> takes a T and returns bool. It is similar to Func<T, bool>.

Lambdas

A lambda expression is an inline, nameless method. The arrow => separates the parameters from the body: x => x * 2. For several statements, use braces.

Events

An event is a controlled way for a class to say "something happened" without knowing who is listening. Other code subscribes with +=. The publisher raises the event, and all subscribers run. Only the publisher can raise it. Outsiders can subscribe or unsubscribe, nothing else.

// Func and Action
Func<int, int, int> add = (a, b) => a + b;
Action<string> log = message => Console.WriteLine($"LOG: {message}");
log($"2 + 3 = {add(2, 3)}");

// Passing behaviour to a method
var words = new List<string> { "banana", "kiwi", "apple", "fig" };
words.Sort((x, y) => x.Length.CompareTo(y.Length));
Console.WriteLine(string.Join(", ", words));

Console.WriteLine(ApplyTwice(5, n => n * 3));

// A closure captures a variable, not its value
int factor = 10;
Func<int, int> scale = n => n * factor;
Console.WriteLine(scale(2));   // 20
factor = 100;
Console.WriteLine(scale(2));   // 200

// Events
var downloader = new Downloader();
downloader.Progress += (sender, e) => Console.WriteLine($"  {e.Percent}%");
downloader.Completed += OnCompleted;
downloader.Start("report.pdf");
downloader.Completed -= OnCompleted;   // unsubscribe when done
downloader.Start("second.pdf");

static void OnCompleted(object? sender, string file) =>
    Console.WriteLine($"Finished {file}");

static int ApplyTwice(int value, Func<int, int> operation) => operation(operation(value));

class ProgressEventArgs(int percent) : EventArgs
{
    public int Percent { get; } = percent;
}

class Downloader
{
    public event EventHandler<ProgressEventArgs>? Progress;
    public event EventHandler<string>? Completed;

    public void Start(string file)
    {
        Console.WriteLine($"Downloading {file}");
        for (int percent = 50; percent <= 100; percent += 50)
        {
            Progress?.Invoke(this, new ProgressEventArgs(percent));
        }
        Completed?.Invoke(this, file);
    }
}

Walking through it

add is a variable holding a function. You call it like a method. log is an Action that returns nothing. These are small, but they are the foundation of LINQ, Task.Run, ASP.NET middleware and most callback code.

The Sort call receives a comparison lambda. Instead of writing a separate class that implements IComparer, I state the rule at the point of use. ApplyTwice is a higher-order method: it takes a function and calls it. The lambda n => n * 3 is passed in, and the result for 5 is 45.

The closure part matters. The lambda n => n * factor uses a variable from the surrounding code. It captures the variable itself, not a copy of its value at that moment. After factor = 100, the same lambda gives a different answer. This is useful, and it is also the root of strange bugs. The classic one is creating lambdas in a for loop that all capture the same loop variable. A foreach variable is fresh each iteration, so it is safe. A for variable is shared.

For events, the convention is EventHandler<TEventArgs>. The handler gets the sender and an arguments object. In Start, I raise the events with ?.Invoke. The question mark skips the call when nobody has subscribed. Without it, raising an event with no subscribers throws NullReferenceException.

The last lines unsubscribe with -=. The second Start call prints no "Finished" line, because the handler is gone. I used a named method for Completed because you cannot unsubscribe a lambda unless you kept it in a variable. That points to the main danger of events: the publisher holds a reference to every subscriber. If a short-lived object subscribes to a long-lived publisher and never unsubscribes, it cannot be garbage collected. That is a memory leak, and it is common in desktop and Blazor applications.

Common mistakes

  • Not unsubscribing from events of long-lived objects.
  • Raising an event without ?.Invoke, which crashes when there are no subscribers.
  • Capturing a for loop variable in a lambda that runs later.
  • Doing slow work in an event handler. The publisher waits for every handler, one after another.
  • Using async void handlers carelessly. Exceptions inside them cannot be caught by the caller. We deal with that in the async lessons.

Try it yourself

  1. Write a method Retry(Func<bool> action, int times) that calls the action until it returns true or the attempts run out.
  2. Add a Cancelled event to the downloader and raise it when a file name is empty.
  3. Build a list of five Action delegates in a for loop that print the loop counter. Run them and explain the output. Then fix it by copying the variable inside the loop.
csharp
// Func and Action
Func<int, int, int> add = (a, b) => a + b;
Action<string> log = message => Console.WriteLine($"LOG: {message}");
log($"2 + 3 = {add(2, 3)}");

// Passing behaviour to a method
var words = new List<string> { "banana", "kiwi", "apple", "fig" };
words.Sort((x, y) => x.Length.CompareTo(y.Length));
Console.WriteLine(string.Join(", ", words));

Console.WriteLine(ApplyTwice(5, n => n * 3));

// A closure captures a variable, not its value
int factor = 10;
Func<int, int> scale = n => n * factor;
Console.WriteLine(scale(2));   // 20
factor = 100;
Console.WriteLine(scale(2));   // 200

// Events
var downloader = new Downloader();
downloader.Progress += (sender, e) => Console.WriteLine($"  {e.Percent}%");
downloader.Completed += OnCompleted;
downloader.Start("report.pdf");
downloader.Completed -= OnCompleted;   // unsubscribe when done
downloader.Start("second.pdf");

static void OnCompleted(object? sender, string file) =>
    Console.WriteLine($"Finished {file}");

static int ApplyTwice(int value, Func<int, int> operation) => operation(operation(value));

class ProgressEventArgs(int percent) : EventArgs
{
    public int Percent { get; } = percent;
}

class Downloader
{
    public event EventHandler<ProgressEventArgs>? Progress;
    public event EventHandler<string>? Completed;

    public void Start(string file)
    {
        Console.WriteLine($"Downloading {file}");
        for (int percent = 50; percent <= 100; percent += 50)
        {
            Progress?.Invoke(this, new ProgressEventArgs(percent));
        }
        Completed?.Invoke(this, file);
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account