Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 182 ยท Delegates, Events and LINQ

Delegates

Learn C# delegates: delegate types, Func, Action and Predicate, method groups, multicast, safe invocation, callbacks, strategies and allocation costs.

Most of the time you tell a program what to do by writing code in a fixed place. But sometimes the decision has to be made by the caller: "sort these, but I'll tell you how to compare two items", "download this file, and call me back when you finish", "retry this operation up to three times". For that, you need to pass a piece of behavior around like a value. In C#, the type that makes this possible is the delegate.

A delegate is a type-safe reference to a method. You can store it in a variable, pass it as an argument, return it from a method and call it later. Lambdas (see lambda expressions), events (next lesson) and LINQ (LINQ basics) are all built on delegates, so this lesson is the foundation for a whole chapter. You will learn how to declare delegate types, the standard Func and Action families, how to point a delegate at a method, multicast delegates, safe invocation, real-world patterns such as callbacks and strategies, and what delegates cost.

What a delegate is

Think of a delegate as a variable that holds "a method with this signature". Here is the oldest form: you declare a delegate type with the delegate keyword, which looks like a method signature without a body:

C# Declaring and using a delegate type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Operation is now a type that can refer to any method that takes two ints and returns an int. The assignment op = Add works because Add matches that signature exactly (parameter types and return type). Writing op(3, 4) calls whichever method the delegate currently points to; it's shorthand for op.Invoke(3, 4).

The compiler turns a delegate declaration into a sealed class derived from System.MulticastDelegate. Each delegate object stores the target (the object whose instance method it calls, or null for a static method) and the method. You never write that class yourself.

A delegate matches by signature, not by name. A delegate type Operation and a second type Calculator declared with the same signature are different types, and a value of one cannot be assigned to the other without wrapping.

Func, Action and Predicate: the standard delegates

Declaring a new type for each signature would be tedious, so the library ships generic delegates that cover nearly every need (see generic methods and delegates):

Delegate Signature Typical use
Action, Action<T1, T2, ...> void (T1, T2, ...) do something, return nothing
Func<TResult>, Func<T1, ..., TResult> TResult (T1, ...) compute a value; the last type argument is the result
Predicate<T> bool (T) a yes/no test (older APIs such as List<T>.FindAll)
Comparison<T> int (T, T) ordering for Sort

In new code, prefer Func and Action over custom delegate types unless a name documents the intent (as Predicate or a domain-specific type like PriceRule might):

C# Func, Action and Predicate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Method groups and instance methods

You can assign a method to a delegate by just writing its name (a method group). For an instance method, the delegate also remembers the object, so calling the delegate runs the method on that specific object:

C# Delegates remember their target

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This "method plus object" pairing is what makes delegates handy for callbacks: the receiver doesn't need to know anything about Counter.

Delegates as parameters: callbacks and strategies

Passing a delegate lets a method be configured by its caller. A callback is a delegate you hand to code that will call you back when something happens. A strategy is a delegate that selects an algorithm. Both are the same technique:

C# Callbacks and strategies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

ProcessAll has no idea what the caller does with progress; it could print, update a bar or log. The strategy table replaces a growing switch statement with data. To add a new pricing rule, add one dictionary entry; the code that applies it never changes (the open/closed principle, see designing with objects).

Multicast delegates

Every delegate can hold a list of methods. The += operator appends one; -= removes one; calling the delegate runs the whole list in order. This is the mechanism behind events.

C# Combining delegates with += and -=

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Facts to remember:

  • Starting with null and using += is fine: null + handler is just handler.
  • Removing needs the same method and target. Removing a lambda by writing the same lambda text again does not work, because it's a different object; keep the lambda in a variable if you'll unsubscribe.
  • Handlers run in the order they were added, on the calling thread, one after another.
  • Delegates are immutable: += creates a new delegate object and stores it in the variable.

Return values and exceptions

When a multicast delegate has a return value, the caller only receives the result of the last handler. And if one handler throws, the exceptions stops the chain: later handlers never run. When it matters, iterate over GetInvocationList() yourself:

C# Multicast return values and exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first try shows "step 1" then the failure, and "step 3" never runs. Looping over the invocation list lets every handler run even when one fails, which is what robust event-raising code does.

Invoking safely: null, ?.Invoke and thread safety

Calling a null delegate throws NullReferenceException. An uninitialized delegate field is null, and a multicast delegate becomes null again if you remove its last handler. Use the null-conditional operator ?.Invoke(...):

C# Calling a delegate that might be null

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

?.Invoke evaluates the delegate variable once into a temporary, which also protects against another thread setting the variable to null between your check and your call. The old pattern if (handler != null) handler(x); has a race on a shared field, since the field could change between the check and the call; handler?.Invoke(x) doesn't.

Anonymous methods: the older lambda

Before lambdas arrived in C# 3.0, you wrote inline delegate bodies with the delegate keyword. These anonymous methods still compile, and you will see them in older code:

C#
Func<int, int, int> add = delegate (int a, int b) { return a + b; };

They differ from lambdas in a few ways:

  • Parameter types are always written out, and the body is always a block with return; there is no expression form such as (a, b) => a + b.
  • You may omit the parameter list entirely (delegate { ... }) when the code ignores the parameters. That works for any delegate type whose parameters are not out, which is why button.Click += delegate { ... }; was popular.
  • Like lambdas, they capture variables, not values, so every call sees the current value of a captured variable.
  • They can be marked static to forbid capturing, just like a static lambda.
C# Anonymous methods next to lambdas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In new code write lambdas: they are shorter and can be inferred. Use an anonymous method only when you want the parameter list omitted, or when you maintain code that already uses them.

Returning delegates and closures

Methods can return delegates, which is how you build configurable behavior. The returned lambda keeps alive any variables it uses (a closure):

C# Delegate factories and composition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Higher-order functions like Compose and RetryOnce are small but powerful. Middleware pipelines in ASP.NET Core are built this way: each step is a delegate wrapping the next one.

Delegate allocations and performance

Each delegate is an object on the heap, so creating one allocates. The compiler caches some of them for you:

  • A lambda that captures nothing (or a method group of a static method) is created once and reused from a hidden static field in current compilers.
  • A lambda that captures a local variable needs a closure object, created when the scope that declares the variable is entered, plus a delegate. If the variable lives inside a loop body, both are allocated again in every iteration (the demo below).
  • Instance-method groups (obj.Method) allocate a new delegate each time they are converted (cache one in a field if you do it in a hot path).

Mark lambdas static to make sure they capture nothing; the compiler then rejects any accidental capture. We can measure the difference on the current thread:

C# Counting delegate allocations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

For most application code this cost is irrelevant; the clarity of delegates wins. In tight loops, generic code over a struct implementing an interface (or a static abstract method, see generic math) avoids the delegate call and its allocation. A delegate call is also about as costly as a virtual method call, a few nanoseconds, and cannot be inlined by the JIT in most cases.

Pitfalls and good practice

  • Prefer Func/Action to hand-made delegate types; create your own when the name carries meaning or you need ref/out parameters, which Func cannot express.
  • Null-check or use ?.Invoke for optional callbacks, and consider defaulting to a no-op (Action<string> log = _ => { };) so the code never has to ask.
  • Don't capture loop variables carelessly; capturing in for shares one variable across all closures, while foreach creates a fresh one per iteration.
  • Unsubscribe what you subscribe. A delegate that points to an instance method keeps that object alive; a long-lived delegate (a static event) can leak short-lived objects. The next lesson on events covers this.
  • Long-running or async callbacks: an async lambda assigned to an Action becomes async void, whose exceptions crash the process. Use Func<Task> for asynchronous callbacks.
  • Remember what multicast returns. Only the last handler's value comes back; iterate GetInvocationList() if you need all of them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which type represents a method that takes a string and returns an int?

    In the Func family the last type argument is the return type, so Func<string, int> takes a string and returns an int. Action never returns a value.
  2. 2. What does a Func<int> delegate with three handlers return when invoked normally?

    All handlers run in order, but only the value returned by the last one comes back. Use GetInvocationList() to collect every result.
  3. 3. Why is handler?.Invoke(arg) preferred to if (handler != null) handler(arg); on a shared field?

    The null-conditional operator copies the field to a temporary before checking, avoiding a race. It also removes the clutter of the explicit check.
  4. 4. Which lambda is guaranteed not to allocate a closure object?

    A static lambda cannot capture locals or this, so the compiler can cache a single delegate instance for it.
  5. 5. What happens if the first handler in a multicast Action throws an exception?

    Invocation stops at the first unhandled exception. To run every handler regardless, loop over GetInvocationList() and catch exceptions individually.

Summary

  • A delegate is a type-safe, object-oriented reference to a method (plus its target object, for instance methods); declare types with delegate, or use Func, Action, Predicate<T> and Comparison<T>.
  • Assign a lambda or a method group to a delegate variable and call it like a method, or via Invoke.
  • Multicast delegates hold a list: += adds, -= removes, handlers run in order, only the last return value is kept, and an exception stops the chain.
  • Use ?.Invoke(...) to call a delegate that may be null.
  • Delegates enable callbacks, strategies, composition and pipelines.
  • Delegates are heap objects: capturing lambdas allocate; static lambdas and cached delegates avoid it.
  • Use Func<Task> rather than Action for asynchronous callbacks, and unsubscribe long-lived delegates.

Next: Events