Multicast delegate
In this chapter you will learn:
- How to use multicast delegate
- Example to create multicast delegate
- Subtract delegate
- Use new operator to create delegate
Use multicast delegate
C# overloads the +
and -
operators for delegate.
By using +
and -
we can add methods to or
subtract methods from a delegate type variable.
delegateVariable += aMethod;
can be rewritten as
delegateVariable = delegateVariable + aMethod;
Example to create multicast delegate
using System;/*from ja va2s . 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.
Subtract delegate
We can subtract delegate method as well.
using System;/* j a v a 2s . com*/
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.
Use new operator to create delegate
using System;/*from j a va 2s . co 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:
Home » C# Tutorial » delegate, lambda, event