CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
method pointed to is irrelevant). Here, we have created a class named SimpleMath, which defines two
static methods that match the pattern defined by the BinaryOp delegate.
When you want to insert the target method to a given delegate object, simply pass in the name of
the method to the delegate’s constructor:
// Create a BinaryOp delegate object that
// "points to" SimpleMath.Add().
BinaryOp b = new BinaryOp(SimpleMath.Add);
At this point, you are able to invoke the member pointed to using a syntax that looks like a direct
function invocation:
// Invoke() is really called here!
Console.WriteLine("10 + 10 is {0}", b(10, 10));
Under the hood, the runtime actually calls the compiler-generated Invoke() method on your
MulticastDelegate der ived class. You can verify this for yourself if you open your assembly in ildasm.exe
and examine the CIL code within the Main() method:
.method private hidebysig static void Main(string[] args) cil managed
{
...
callvirt instance int32 SimpleDelegate.BinaryOp::Invoke(int32, int32)
}
C# does not require you to explicitly call Invoke() within your code base. Because BinaryOp can
point to methods that take two arguments, the following code statement is also permissible:
Console.WriteLine("10 + 10 is {0}", b.Invoke(10, 10));
Recall that .NET delegates are type safe. Therefore, if you attempt to pass a delegate a method that
does not match the pattern, you receive a compile-time error. To illustrate, assume the SimpleMath class
now defines an additional method named SquareNumber(), which takes a single integer as input:
public class SimpleMath
{
...
public static int SquareNumber(int a)
{ return a * a; }
}
Given that the BinaryOp delegate can point only to methods that take two integers and return an
integer, the following code is illegal and will not compile:
// Compiler error! Method does not match delegate pattern!
BinaryOp b2 = new BinaryOp(SimpleMath.SquareNumber);
Investigating a Delegate Object
Let’s spice up the current example by creating a static method (named DisplayDelegateInfo()) within
the Program class. This method will print out the names of the method(s) maintained by a delegate
object, as well as the name of the class defining the method. To do this, we will iterate over the
System.Delegate array returned by GetInvocationList(), invoking each object’s Target and Method
properties:
365