Simple and Multicast Delegates in C#

In C#, delegates represent methods that are callable without knowledge of the target object. Delegates enable scenarios that some other languages have addressed with function pointers. However, unlike function pointers, delegates are object-oriented and type-safe.

There are three steps in defining and using delegates: declaration, instantiation, and invocation.

Delegate Declaration

public class DeligateClass
{
    public DeligateClass()
    {
    }
    // Declare a delegate
    public delegate void MessageHandler(string message);
    // The use of the delegate.
    public void Process(MessageHandler handler)
    {
        if (handler != null)
            handler("Begin Message");
        if (handler != null)
            handler("End Message");
    }
}

Function Class

This class contains the functions will be called by delegates

public class FunctionClass
{
    public FunctionClass()
    {
    }
    //This method will show alert message to user
    public static void AlertMessage(string s)
    {
        System.Windows.Forms.MessageBox.Show(s);
    }
    //This method will write output to console
    public static void ConsoleMessage(string s)
    {
        Console.WriteLine(s);
    }
} 

Instantiation and Invocation

Client Application to use the defined Delegate

Simple Delegate

Create a windows form and add one button to it and paste the following code on its click event.

private void button1_Click(object sender, System.EventArgs e)
{
    //Instantiating a delegate
    DeligateClass dc = new DeligateClass();
    DeligateClass.MessageHandler ll = null;
    ll += new DeligateClass.MessageHandler(FunctionClass.AlertMessage);
    //Calling a delegate
    dc.Process(ll);
}

When you will click on button1, it will show 'Begin Message' and 'End Message' message box.

Multicast Delegate

Add one more button to form with following code.

private void button2_Click(object sender, System.EventArgs e)
{
    DeligateClass dc = new DeligateClass();
    DeligateClass.MessageHandler ll = null;
    ll += new DeligateClass.MessageHandler(FunctionClass.AlertMessage);
    ll += new DeligateClass.MessageHandler(FunctionClass.ConsoleMessage);
    dc.Process(ll);
}

When you will click on button2, in addition to 'Begin Message' and 'End Message' message box, it will also write to console of visual studio (VS).

Delegates and interfaces are similar in that they enable the separation of specification and implementation. Multiple independent authors can produce implementations that are compatible with an interface specification. Similarly, a delegate specifies the signature of a method, and authors can write methods that are compatible with the delegate specification. There are direction defined by Microsoft when to use delegate and when to use interface.

Delegates are ideally suited for use as events - notifications from one component to "listeners" about changes in that component. 


Similar Articles