«^»
10. Delegates

In its simplest form, a delegate is a type representing the signature of a method. For example:

delegate int Massage(string s);

declares a new type called Massage that is the type of methods that take a string and return an int. Perhaps:

delegate int:(string s) Massage;

would have been better syntax.

If we now write:

private static void iProcess(Massage pMassage)
{
    string tString = Console.ReadLine();
    int tInt = pMassage(tString);
    Console.WriteLine(tInt);
}

then what a call of iProcess such as:

iProcess(tMassage);

will do depends on the value of the delegate variable tMassage. We could have:

Massage tMassage = new Massage(StringLength);
iProcess(tMassage);

where StringLength is declared as:

private static int StringLength(string pString)
{
    return pString.Length;
}

Here tMassage is made to point to the StringLength method.

A method like iProcess is sometimes called a higher order method as it is written in terms of a pointer to a method (which is passed as a parameter).

If a delegate's return type is void, a delegate variable can be assigned a value that represents (not just one method but) a list of methods to be called:

delegate void Display(string s);
private static void iProcess(Display pDisplay)
{
    string tString = Console.ReadLine();
    pDisplay(tString);
}
private static void All(string pString)
{
    Console.WriteLine(pString);
}
private static void FirstTwo(string pString)
{
    Console.WriteLine(pString.Substring(0, 2));
}
public static void Main()
{
    Display tDisplay = new Display(All) + new Display(FirstTwo);
    iProcess(tDisplay);
}

Here tDisplay is assigned a list of methods, and so when it gets called:

pDisplay(tString)

each method of the list will get executed in turn. This use of delegates is called a multicast.

Although delegates are not part of Java, they appeared in Microsoft's Visual J++. Sun Microsystems' criticisms of delegates are given at [8].