Delegates
In this page:
Delegates
A delegate is a type-safe reference to a method, letting you pass methods around as values — as parameters, return values, or stored in variables. You declare a delegate type describing the method signature it can point to, then assign any matching method to it. Calling the delegate invokes whichever method it currently references.
Note: Delegates are the foundation that lambda expressions, Func<>/Action<>, and events are all built on.
Example: Delegates
using System;
delegate int Operation(int a, int b);
class Program
{
static int Add(int a, int b) => a + b;
static int Multiply(int a, int b) => a * b;
static void Main(string[] args)
{
Operation op = Add;
Console.WriteLine(op(3, 4));
op = Multiply;
Console.WriteLine(op(3, 4));
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: