Combine Delegates (Multicast Delegates) C# with Example



Combine Delegates (Multicast Delegates) C# with Example

Addition + and subtraction - operations can be used to combine delegate instances. The delegate contains a list of 
the assigned delegates. 
using System; 
using System.Reflection; 
using System.Reflection.Emit; 
namespace DelegatesExample { 
class MainClass { 
private delegate void MyDelegate(int a); 
private static void PrintInt(int a) { 
Console.WriteLine(a); 
} 
private static void PrintType(T a) { 
Console.WriteLine(a.GetType()); 
} 
public static void Main (string[] args) 
{ 
MyDelegate d1 = PrintInt; 
MyDelegate d2 = PrintType; 
// Output: 
// 1 
d1(1); 
// Output: 
// System.Int32 
d2(1); 
MyDelegate d3 = d1 + d2; 
// Output: 
// 1 
// System.Int32 
d3(1); 
MyDelegate d4 = d3 - d2; 
// Output: 
// 1 
d4(1); 
// Output: 
// True 
Console.WriteLine(d1 == d4); 
 

} 
} 
} 
In this example d3 is a combination of d1 and d2 delegates, so when called the program outputs both 1 and 
System.Int32 strings. 
Combining delegates with non void return types: 
If a multicast delegate has a nonvoid return type, the caller receives the return value from the last method to be 
invoked. The preceding methods are still called, but their return values are discarded. 
class Program 
{ 
public delegate int Transformer(int x); 
static void Main(string[] args) 
{ 
Transformer t = Square; 
t += Cube; 
Console.WriteLine(t(2)); // O/P 8 
} 
static int Square(int x) { return x * x; } 
static int Cube(int x) { return x*x*x; } 
} 
t(2) will call first Square and then Cube. The return value of Square is discarded and return value of the last method 
i.e. Cube is retained. 

0 Comment's

Comment Form

Submit Comment