Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0184 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; using System; 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: 1 second:1 The delegates are called in the sequence of adding. We can subtract delegate method as well. using System; 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 output: second:1