Delegates
A delegate wires up a method caller to its target method at runtime. There are two aspects to a delegate: type and instance. A delegate type defines a protocol to which the caller and target will conform, comprising a list of parameter types and a return type. A delegate instance is an object that refers to one (or more) target methods conforming to that protocol.
A delegate instance literally acts as a delegate for the caller: the caller invokes the delegate, and then the delegate calls the target method. This indirection decouples the caller from the target method.
A delegate type declaration is preceded by the keyword delegate,
but otherwise it resembles an (abstract) method declaration. For
example:
delegate int Transformer (int x);
To create a delegate instance, you can assign a method to a delegate variable:
class Test
{
static void Main()
{
Transformer t = Square; // Create delegate instance
int result = t(3); // Invoke delegate
Console.Write (result); // 9
}
static int Square (int x) { return x * x; }
}Invoking a delegate is just like invoking a method (since the delegate’s purpose is merely to provide a level of indirection):
t(3);
The statement Transformer t =
Square is shorthand for:
Transformer t = new Transformer (Square);
And t(3) is shorthand for:
t.Invoke (3);
A delegate is similar to a callback, a general term that captures constructs such as C function pointers.
Writing Plug-in Methods with Delegates
A delegate variable is assigned a method at runtime. This is useful ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access