Free mag vol1 | Page 427

CHAPTER 10  DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS static void DisplayDelegateInfo(Delegate delObj) { // Print the names of each member in the // delegate's invocation list. foreach (Delegate d in delObj.GetInvocationList()) { Console.WriteLine("Method Name: {0}", d.Method); Console.WriteLine("Type Name: {0}", d.Target); } } Assuming you have updated your Main() method to actually call this new helper method: BinaryOp b = new BinaryOp(SimpleMath.Add); DisplayDelegateInfo(b); you would find the output shown next: ***** Simple Delegate Example ***** Method Name: Int32 Add(Int32, Int32) Type Name: 10 + 10 is 20 Notice that the name of the target class (SimpleMath) is currently not displayed when calling the Target property. The reason has to do with the fact that our BinaryOp delegate is pointing to a static method and, therefore, there is no object to reference! However, if we update the Add() and Subtract() methods to be nonstatic (simply by deleting the static keywords), we could create an instance of the SimpleMath class and specify the methods to invoke using the object reference: static void Main(string[] args) { Console.WriteLine("***** Simple Delegate Example *****\n"); // .NET delegates can also point to instance methods as well. SimpleMath m = new SimpleMath(); BinaryOp b = new BinaryOp(m.Add); // Show information about this object. DisplayDelegateInfo(b); } Console.WriteLine("10 + 10 is {0}", b(10, 10)); Console.ReadLine(); In this case, we would find the output shown here: ***** Simple Delegate Example ***** Method Name: Int32 Add(Int32, Int32) Type Name: SimpleDelegate.SimpleMath 366