C# Multicast Delegates
In this chapter you will learn:
- What are Multicast Delegates
- Syntax for Multicast Delegates
- Example for Multicast Delegates
- Subtract delegate
- Use new operator to create delegate
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;/* w ww . ja 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(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. ja v a 2s. 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 -= consolePrinter;
p(1);
}
}
The code above generates the following result.
Example 3
using System;// w ww . j a v a 2 s. c o m
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.
Next chapter...
What you will learn in the next chapter:
C# Multicast Delegates
delegate parametersC# Generic delegate
C# Func and Action
C# Anonymous delegate