Delegates
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 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.
delegate int Transformer (int x);
To
create a delegate instance, you can assign a method to a delegate variable:
public class Test
{
static void
Main()
{
Transformer t = Square; // Create delegate instance
int result = t(3); // Invoke delegate
Console.WriteLine (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:

Join the conversation! Your thoughts help the community grow.