Free mag vol1 | Page 425

CHAPTER 10  DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS Member Meaning in Life GetInvocationList() This method returns an array of System.Delegate objects, each representing a particular method that may be invoked. Remove() RemoveAll() These static methods remove a method (or all methods) from the delegate’s invocation list. In C#, the Remove() method can be called indirectly using the overloaded -= operator. The Simplest Possible Delegate Example To be sure, delegates can cause some confusion when encountered for the first time. Thus, to get the ball rolling, let’s take a look at a very simple Console Application program (named SimpleDelegate) that makes use of the BinaryOp delegate type you’ve seen previously. Here is the complete code, with analysis to follow: namespace SimpleDelegate { // This delegate can point to any method, // taking two integers and returning an integer. public delegate int BinaryOp(int x, int y); // This class contains methods BinaryOp will // point to. public class SimpleMath { public static int Add(int x, int y) { return x + y; } public static int Subtract(int x, int y) { return x - y; } } class Program { static void Main(string[] args) { Console.WriteLine("***** Simple Delegate Example *****\n"); // Create a BinaryOp delegate object that // "points to" SimpleMath.Add(). BinaryOp b = new BinaryOp(SimpleMath.Add); } } // Invoke Add() method indirectly using delegate object. Console.WriteLine("10 + 10 is {0}", b(10, 10)); Console.ReadLine(); } Again, notice the format of the BinaryOp delegate type declaration; it specifies that BinaryOp delegate objects can point to any method taking two integers and returning an integer (the actual name of the 364