Delegates
A delegate is a variable that holds a method, like a phone contact you can call later. It lets you pass actions around like objects.
In this page:
Syntax
delegate ReturnType DelegateName(type parameter);
DelegateName variable = MethodName;
ReturnType result = variable(argument);
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Invoking a null delegate directly, which throws
NullReferenceException; use?.Invoke. - Assigning a method whose signature does not match the delegate type, which is a compile error.
- Confusing calling the method with
Method()and passing it withMethod.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: