A delegate dynamically wires up a method caller to its target method. 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 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 (as the delegate’s purpose is merely to provide a level of indirection):


The statement:

	Transformer t = Square;

is shorthand for:

	Transformer t = new Transformer(Square);


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 dynamically. This is useful for writing plug-in methods. In this example, ...

Get C# 3.0 Pocket Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.