Click here to Skip to main content
Click here to Skip to main content
Go to top

.NET Multicast Delegates

, 2 Dec 2008
Rate this:
Please Sign up or sign in to vote.
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:

/// 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:

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)

Share

About the Author

Cirilo Meggiolaro
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

 
Generalsyntactic sugar Pinmemberwallism17-Dec-08 10:36 
GeneralMy vote of 2 PinmemberMKauffman3-Dec-08 6:51 
GeneralSome additional points Pinmemberervegter3-Dec-08 1:17 
GeneralRe: Some additional points PinmemberAndy Davies4-Dec-08 2:09 
QuestionQuestion PinmemberIlíon2-Dec-08 6:53 
AnswerRe: Question PinmemberPaul Brower2-Dec-08 8:17 
GeneralRe: Question PinmemberIlíon3-Dec-08 9:39 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140926.1 | Last Updated 2 Dec 2008
Article Copyright 2008 by Cirilo Meggiolaro
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid