C# Delegates Explained - Multicast Delegates
(Page 4 of 5 )
As you saw in the MSIL code, the delegate type that we created automatically inherits the System.MulticastDelegate, which provides a functionality that creates a chain of delegates through a linked list. It's better to explain with an example, so let's modify our example to use a multicast delegate.
using System;
namespace Delegates
{
public class Math
{
// note that the delegate now is a nested type of the Math class
public delegate void DelegateToMethod(int x, int y);
public void Add(int first, int second)
{
Console.WriteLine("The method Add() returns {0}", first + second);
}
public void Multiply(int first, int second)
{
Console.WriteLine("The method Multiply() returns {0}", first * second);
}
public void Divide(int first, int second)
{
Console.WriteLine("The method Divide() returns {0}", first / second);
}
}
public class DelegateApp
{
public static void Main()
{
Math math = new Math();
Math.DelegateToMethod multiDelegate = null;
multiDelegate = new Math.DelegateToMethod(math.Add);
multiDelegate += new Math.DelegateToMethod(math.Multiply);
multiDelegate += new Math.DelegateToMethod(math.Divide);
multiDelegate(10,10);
Console.ReadLine();
}
}
}

A multicast delegate is an object that maintains a linked list of delegates. Invoking the delegate invokes each delegate (which in turn calls its encapsulated method) in the same order that it has been added to the linked list. In our example we have created an object (a delegate) called multiDelegate of type Math.DelegateToMethod and assigned a null value to this object.
The next statement assigns (through the assignment = operator as you already know) a new delegate object that encapsulates the method math.Add(). Using the operator += we assign more delegate objects (thus creating a multicast delegate) to the delegate multiDelegate. Then invoking the delegate invokes all the delegates maintained in its linked list, which in turn calls the encapsulated methods.
The statement multiDelegate(10,10); is similar to our previous example in which we have created three delegate objects and then calling each of them separately. You can remove a delegate object from the linked list using the operator -=. Actually, behind the scenes the method Combine() is used to perform the creation of a multicast delegate. In fact this method returns a new delegate instance. If you load the application with ILDASM you will see the use of this method.

Next: Callback Methods through Delegates >>
More C# Articles
More By Michael Youssef