Introduction of Multicast Delegate

Delegates are best complemented as new type of Object in C#. They are also represented as pointer to functions. Technically delegate is a reference type used to encapsulate a method with a specific signature and return type.
  • 1998

Introduction

Delegates are best complemented as new type of Object in C#. They are also represented as pointer to functions. Technically delegate is a reference type used to encapsulate a method with a specific signature and return type. Since in this article delegate discussion is event centric. System. Delegate only identifies one subscriber to an event. System.MulticastDelegate therefore, adds to delegates the support for notifying multiple subscribers. This is enabled through System.MulticastDelegate containment of another System.MulticastDelegate instance. When we add a subscriber to a multicast delegate, the Multicast Delegate class creates a new instance of the delegate type, stores the object reference and the method pointer for the added method into the new instance and adds the new delegate instance as the next item in a list of delegate instances. In effect, the Multicast Delegate class maintains a linked list of delegate objects. Multicast Delegates can hold and invoke multiple methods. In this example we declare a simple delegate called MyDelegateMethod, which can hold and then invoke the MyMethod1 and MyMethod2 methods sequentially.

Example : This is a simple example of a multicast delegate.

Code

using System;

delegate void MyDelegateMethod();

class MyDelegateSample

{

    static void Main()

    {

        new MyDelegateSample();

    }

    MyDelegateSample()

    {

        MyDelegateMethod myMethod = null;

        myMethod += new MyDelegateMethod(MyMethod1);

        myMethod += new MyDelegateMethod(MyMethod2);

        myMethod();

    }

    void MyMethod1()

    {

        Console.WriteLine("In MyMethod1...");

    }

    void MyMethod2()

    {

        Console.WriteLine("In MyMethod2...");

    }

}

© 2013 dotNetheaven. All rights reserved.