Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Types and Literals

Delegates in depth

Reference for C# delegates: Func, Action and Predicate, custom delegate types, multicast invocation, method groups, lambdas, variance and null handling.

A delegate is a type-safe reference to a method. A variable of a delegate type can hold any method (static or instance, named or anonymous) whose parameters and return type match the delegate's signature, and you call it like a method. Delegates are how C# passes behavior around: callbacks, LINQ predicates, event handlers and strategy objects are all delegates.

You rarely need to declare your own. The framework supplies Action (no result), Func (returns a result) and Predicate<T> (returns bool) in many shapes.

C#
Func<int, int, int> add = (a, b) => a + b;
Action<string> log = Console.WriteLine;
Predicate<int> isEven = n => n % 2 == 0;

Try it

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.

C# Multicast delegates and captured variables

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.

Syntax

C#
[modifiers] delegate ReturnType Name<T>(parameters) [where T : constraint];
Built-in type Meaning
Action, Action<T1,...,T16> Takes up to 16 arguments, returns nothing.
Func<TResult>, Func<T1,...,T16,TResult> Takes up to 16 arguments, returns TResult (last type argument).
Predicate<T> bool Predicate<T>(T obj); used by List<T>.FindAll, Exists and similar.
Comparison<T> int Comparison<T>(T x, T y); used by List<T>.Sort.
EventHandler, EventHandler<TArgs> The standard event pattern with object? sender.

Ways to create a delegate: a lambda (x => x + 1), an anonymous method (delegate (int x) { return x; }), a method group (Console.WriteLine), or new Transform(Square). Lambdas may carry attributes and an explicit return type, and C# 10+ infers a natural type for them, so var f = (int x) => x * 2; compiles.

Members: Invoke, DynamicInvoke (slow, late-bound), GetInvocationList, Method, Target. Operators: +, -, +=, -=, ==.

Errors. Invoking a null delegate throws NullReferenceException; use d?.Invoke(). If one target in a multicast delegate throws, the remaining targets do not run.

Usage notes

  • Immutable and multicast. Combining creates a new delegate. Targets run in the order added; for a non-void delegate you get only the last return value, so use GetInvocationList() when you need every result.
  • Closures capture variables, not copies. A lambda that uses a local keeps it alive and sees later changes. In a foreach loop each iteration has its own copy of the loop variable, but a for loop shares one variable across iterations, so lambdas created in a for loop all see its final value.
  • Allocation. A capturing lambda allocates a closure object; a non-capturing one is cached. Mark lambdas static (static x => x + 1) to forbid captures and keep them allocation-free.
  • Variance. Delegate type parameters can be covariant (out on results) or contravariant (in on parameters), so Func<string> converts to Func<object> and Action<object> to Action<string>.
  • Choosing a type. Use Func/Action for simple callbacks; declare a named delegate when the signature is part of your public API and a good name helps, or when you need ref, out or params parameters, which Func/Action cannot express.
  • Events are delegates with restricted access: outside the class only += and -= are allowed.
  • Async. A lambda passed to Action that uses await becomes async void; use Func<Task> instead so exceptions and completion are observable.
  • Equality. Two delegates are equal when they have the same target object and method.