C# Multicast Delegates
Description
All delegate instances have multicast capability.
Syntax
This means that a delegate instance can reference not just a single target method, but also a list of target methods.
The +
and +=
operators combine delegate instances.
For example:
SomeDelegate d = SomeMethod1;
d += SomeMethod2;
The last line is functionally the same as:
d = d + SomeMethod2;
Invoking d
will now call both SomeMethod1
and
SomeMethod2
. Delegates are invoked
in the order they are added.
The -
and -=
operators remove the right delegate operand from the left delegate
operand. For example:
d -= SomeMethod1;
Invoking d
will now cause only SomeMethod2
to be invoked.
Example
Example for Multicast Delegates
using System;/*from w w w. jav a 2 s . c o m*/
delegate void Printer(int i);
class Test
{
static void consolePrinter(int i)
{
Console.WriteLine(i);
}
static void consolePrinter2(int i)
{
Console.WriteLine("second:" + i);
}
static void Main()
{
Printer p = consolePrinter;
p += consolePrinter2;
p(1);
}
}
The output:
The delegates are called in the sequence of adding.
Example 2
We can subtract delegate method as well.
using System;/* w w w. j a va2s . co m*/
delegate void Printer(int i);
class Test
{
static void consolePrinter(int i)
{
Console.WriteLine(i);
}
static void consolePrinter2(int i)
{
Console.WriteLine("second:" + i);
}
static void Main()
{
Printer p = consolePrinter;
p += consolePrinter2;
p -= consolePrinter;
p(1);
}
}
The code above generates the following result.
Example 3
using System;/*w ww.jav a 2s. com*/
class MainClass
{
delegate int MyDelegate(string s);
static void Main(string[] args)
{
string MyString = "Hello World";
MyDelegate Multicast = null;
Multicast += new MyDelegate(DoSomething);
Multicast += new MyDelegate(DoSomething2);
Multicast(MyString);
}
static int DoSomething(string s)
{
Console.WriteLine("DoSomething");
return 0;
}
static int DoSomething2(string s)
{
Console.WriteLine("DoSomething2");
return 0;
}
}
The code above generates the following result.