Multicasting and delegates in C#

Jun 18, 2014

One interesting feature of delegates in C# is that it provide ways to attach / detach more than one methods that has method signature similar to the delegate declared and combine them together.

This combining or attaching / detaching of methods to a delegate is called Multicasting.

Behind the scenes:

This multicasting is possible because delegates inherit from System.MulticastDelegate which in turn inherits from System.Delegate, which inherits from Object class.

How to multicast:

Multicasting can be done using += and / or -= operator.

Here is an example that demonstrate use of += and -= to multicast delegates.

private delegate void Greetings();

static void Main(string[] args)
{
	SayHello();
    Console.ReadLine();
}

public static void SayHelloToScott()
{
	Console.WriteLine("Hi Mr. Delegate, from Scott");
}

public static void SayHelloToAlex()
{
    Console.WriteLine("How about a coffee? from Alex");
}

public static void SayHelloToJasmine()
{
	Console.WriteLine("Hi delegates, from Jasmine");
}

public static void SayHelloToJsinh()
{
    Console.WriteLine("Delegates aahaa, from Jsinh");
}

public static void SayHello()
{
    Greetings greets = SayHelloToScott;
    greets += SayHelloToAlex;
    greets += SayHelloToJasmine;
    greets += SayHelloToJsinh;
    greets();

    Console.WriteLine(Environment.NewLine);
    greets -= SayHelloToAlex;
    greets();

    Console.WriteLine(Environment.NewLine);
    var test = greets.GetInvocationList();
    foreach (var info in test.Select(item => item.GetMethodInfo()))
    {
        Console.WriteLine(info.Name);
	}
}

Output:

Hi Mr. Delegate, from Scott
How about a coffee? from Alex
Hi delegates, from Jasmine
Delegates aahaa, from Jsinh

Hi Mr. Delegate, from Scott
Hi delegates, from Jasmine
Delegates aahaa, from Jsinh

SayHelloToScott
SayHelloToJasmine
SayHelloToJsinh

More

System.MulticastDelegate contains a method GetInvocationList(). It provides a list of Delegate instance which are attached to this delegate instance.

Happy Coding !!