Delegate (C#)

A delegate is a type that holds a reference to a method, letting you store and pass methods around like variables. It is the foundation of callbacks, events, and LINQ in C#.

C#

Once you have a delegate variable, you can assign different methods to it and call it as if it were the method itself. Built-in generic delegates Func<> (returns a value) and Action<> (returns void) cover most needs.

Delegates make code flexible: a method can accept a delegate parameter and call back into code the caller supplies.

Syntax

Func<int, int> name = x => x * 2;

Examples

C#

Func<int, int> square = x => x * x;
Action<string> shout = s => Console.WriteLine(s.ToUpper());

Console.WriteLine(square(4));
shout("hi");

Output:

16
HI

Learn it in a lesson

See also

Back to the Dictionary