Skip to content

Delegates

Context: Delegates are type‑safe function pointers that reference methods with a specific signature. They enable callbacks, event handling, and flexible method invocation.

A delegate defines the signature of a method. You can assign any matching method to a delegate variable and invoke it.

public delegate int MathOperation(int a, int b);
public static int Add(int x, int y) => x + y;
public static int Multiply(int x, int y) => x * y;
MathOperation op = Add;
int result = op(3, 4); // 7

Callback methods in asynchronous programming: Delegates are used to pass callback methods to asynchronous operations, allowing code to run when the operation completes.

Example: In .NET, Action<T> and Func<TResult> are generic delegates used extensively in LINQ, Task Parallel Library, and event handling.