X hits on this document





310 / 396

Chapter ‎18   Unsafe code

that method had directly called the method to which that delegate referred.

Invocation of a delegate instance whose invocation list contains multiple entries proceeds by invoking each of the methods in the invocation list, synchronously, in order. Each method so called is passed the same set of arguments as was given to the delegate instance. If such a delegate invocation includes reference parameters (§‎, each method invocation will occur with a reference to the same variable; changes to that variable by one method in the invocation list will be visible to methods further down the invocation list. If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.

If an exception occurs during processing of the invocation of such a delegate, and that exception is not caught within the method that was invoked, the search for an exception catch clause continues in the method that called the delegate, and any methods further down the invocation list are not invoked.

Attempting to invoke a delegate instance whose value is null results in an exception of type System.NullReferenceException.

The following example shows how to instantiate, combine, remove, and invoke delegates:

using System;

delegate void D(int x);

class C { public static void M1(int i) { Console.WriteLine("C.M1: " + i); }

public static void M2(int i) { Console.WriteLine("C.M2: " + i); }

public void M3(int i) { Console.WriteLine("C.M3: " + i); } }

class Test { static void Main() { D cd1 = new D(C.M1); cd1(-1);// call M1

D cd2 = new D(C.M2); cd2(-2);// call M2

D cd3 = cd1 + cd2; cd3(10);// call M1 then M2

cd3 += cd1; cd3(20);// call M1, M2, then M1

C c = new C(); D cd4 = new D(c.M3); cd3 += cd4; cd3(30);// call M1, M2, M1, then M3

cd3 -= cd1;// remove last M1 cd3(40);// call M1, M2, then M3

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.297

Document info
Document views1226
Page views1226
Page last viewedThu Jan 19 15:07:28 UTC 2017