Click here to Skip to main content
15,886,110 members
Articles / Desktop Programming / Windows Forms

.NET Multicast Delegates

Rate me:
Please Sign up or sign in to vote.
4.29/5 (25 votes)
2 Dec 2008CPOL1 min read 96.4K   924   53   8
Multicast delegates provide functionality to execute more than one method.

Introduction

Multicast delegates provide functionality to execute more than one method.

Internally, a linked list of delegates (called Invocation List) is stored, and when the multicast delegate is invoked, the list of delegates will be executed in sequence.

How to…

The simplest way to start working with multicast delegates is to create single delegates and combine them to a multicast delegate, as described in the following code snippet:

C#
/// Declares the multicast delegate
public delegate void myDel(); 

static public void Main(string[] args)
{
    /// Declares the single delegate that points to MethodA
    myDel myDelA = new myDel(MethodA);
    /// Declares the single delegate that points to MethodA
    myDel myDelB = new myDel(MethodB);
    /// Declares the multicast delegate combining both delegates A and B
    myDel myMultiCast = (myDel)Delegate.Combine(myDelA, myDelB);
    /// Invokes the multicast delegate
    myMultiCast.Invoke();
}

static void MethodA()
{
    Console.WriteLine("Executing method A.");
}

static void MethodB()
{
    Console.WriteLine("Executing method B.");
}

Here is the output:

Executing method A.
Executing method B.

Deriving a class from the MulticastDelegate class

The Delegate and MulticastDelegate classes cannot be derived explicitly, but there’s a way to do that.

The following example defines three classes named Order, Stock, and Receipt beyond the main method, from a console application, for example:

  1. The Order class holds the delegate that defines the methods signature, and provides methods to add product items to the order, and a checkout method that will use a delegate as a parameter to define what method to call. It can be used for single delegates or a multicast delegate.
  2. The Stock class has an operation to remove the products from the stock.
  3. The Receipt class has an operation to print an item to the receipt.
  4. The Main method creates an instance of the Order type, adding product items to the order, and creates the multicast delegate based on a combination of two derived delegates.

Let’s check the code:

C#
class Order
{
    /// Main order delegate
    public delegate void myOrderDel(int prodId, int quantity);

    /// Stores a dictionary of products ids and respective quantities
    private static HybridDictionary prodList = new HybridDictionary();

    public void AddItem(int prodId, int quantity)
    {
        /// Add products and quantitites to the dictionary.
        prodList.Add(prodId, quantity);
    }

    public static void Checkout(myOrderDel multicastDelegate)
    {
        /// Loop through all products in the dictionary
        foreach (DictionaryEntry prod in prodList)
        {
            /// Invoke the multicast delegate
            multicastDelegate.Invoke(Convert.ToInt32(prod.Key), 
                                     Convert.ToInt32(prod.Value));
        }
    }
}

class Stock
{
    public static void Remove(int prodId, int quantity)
    {
        Console.WriteLine("{0} unit(s) of the product {1} has/have" + 
                          " been removed from the stock.", quantity, prodId);
    }
}

class Receipt
{
    public static void PrintItem(int prodId, int quantity)
    {
        Console.WriteLine("{0} unit(s) of the product {1} has/have been" + 
                          " printed to the receipt.", quantity, prodId);
    }
}

static public void Main(string[] args)
{
    /// Create the order object
    Order myOrder = new Order();

    /// Add products and quantities to the order
    myOrder.AddItem(1, 2);
    myOrder.AddItem(2, 3);
    myOrder.AddItem(3, 1);
    myOrder.AddItem(4, 1);
    myOrder.AddItem(5, 4);

    /// Order delegate instance pointing to Stock class.
    Order.myOrderDel myStockDel = new Order.myOrderDel(Stock.Remove);

    /// Receipt delegate instance pointing to Receipt class.
    Order.myOrderDel myReceiptDel = new Order.myOrderDel(Receipt.PrintItem);

    /// Combine the two previous delegates onto the multicast delegate.
    Order.myOrderDel myMulticastDel = 
      (Order.myOrderDel)Delegate.Combine(myStockDel, myReceiptDel);

    /// Invoke the checkout method passing the multicast delegate
    Order.Checkout(myMulticastDel);
}

Here is the output:

2 unit(s) of the product 1 has/have been removed from the stock.
2 unit(s) of the product 1 has/have been printed to the receipt.
3 unit(s) of the product 2 has/have been removed from the stock.
3 unit(s) of the product 2 has/have been printed to the receipt.
1 unit(s) of the product 3 has/have been removed from the stock.
1 unit(s) of the product 3 has/have been printed to the receipt.
1 unit(s) of the product 4 has/have been removed from the stock.
1 unit(s) of the product 4 has/have been printed to the receipt.
4 unit(s) of the product 5 has/have been removed from the stock.
4 unit(s) of the product 5 has/have been printed to the receipt.

The MSDN site provides another nice example about how to derive a class (not in an explicit way) from a MulticastDelegate class. Click here to read!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
Canada Canada
I am a brazilian architect / development team lead located in Toronto, Canada.

During the last years I have been working on enterprise applications especially on Microsoft platform for companies located in South and North America.

Application design, coding and especially tunning, debugging and performance related issues troubleshooting make part of my skills bag.

I keep a blog called ITTecture with daily tips related to architecture, performance and .NET coding where you will find some tips, tricks, thoughts and even concepts related to system architecture, application performance and all the cool (but sometimes not so cool) stuff that I’ve heard, read, debbuged, fixed, refactored and coded and how to avoid long overnights far away from home!!!

Comments and Discussions

 
QuestionGet the list of methods contained by Multicast delegate Pin
Ammar Shaukat23-Jan-18 2:15
professionalAmmar Shaukat23-Jan-18 2:15 
Generalsyntactic sugar Pin
wallism17-Dec-08 10:36
wallism17-Dec-08 10:36 
GeneralMy vote of 2 Pin
MKauffman3-Dec-08 6:51
MKauffman3-Dec-08 6:51 
GeneralSome additional points PinPopular
ervegter3-Dec-08 1:17
ervegter3-Dec-08 1:17 
GeneralRe: Some additional points Pin
Andy Davies4-Dec-08 2:09
Andy Davies4-Dec-08 2:09 
QuestionQuestion Pin
Ilíon2-Dec-08 6:53
Ilíon2-Dec-08 6:53 
AnswerRe: Question Pin
Paul Brower2-Dec-08 8:17
Paul Brower2-Dec-08 8:17 
GeneralRe: Question Pin
Ilíon3-Dec-08 9:39
Ilíon3-Dec-08 9:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.