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.
Func<int, int, int> add = (a, b) => a + b; Action<string> log = Console.WriteLine; Predicate<int> isEven = n => n % 2 == 0;
Try it
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.
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
[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-
voiddelegate you get only the last return value, so useGetInvocationList()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
foreachloop each iteration has its own copy of the loop variable, but aforloop shares one variable across iterations, so lambdas created in aforloop 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 (
outon results) or contravariant (inon parameters), soFunc<string>converts toFunc<object>andAction<object>toAction<string>. - Choosing a type. Use
Func/Actionfor simple callbacks; declare a named delegate when the signature is part of your public API and a good name helps, or when you needref,outorparamsparameters, whichFunc/Actioncannot express. - Events are delegates with restricted access: outside the class only
+=and-=are allowed. - Async. A lambda passed to
Actionthat usesawaitbecomesasync void; useFunc<Task>instead so exceptions and completion are observable. - Equality. Two delegates are equal when they have the same target object and method.
Related
delegate,event, Anonymous types, Type conversions- Lessons: Delegates, Lambdas, Events