13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>C#</strong> LANGUAGE SPECIFICATIONusing System;delegate void D(int x);class Test{public static void M1(int i) {Console.WriteLine("Test.M1: " + i);}public static void M2(int i) {Console.WriteLine("Test.M2: " + i);}public void M3(int i) {Console.WriteLine("Test.M3: " + i);}}class Demo{static void Main() {D cd1 = new D(Test.M1);cd1(-1); // call M1D cd2 = new D(Test.M2);cd2(-2); // call M2D cd3 = cd1 + cd2;cd3(10); // call M1 then M2cd3 += cd1;cd3(20); // call M1, M2, then M1Test t = new Test();D cd4 = new D(t.M3);cd3 += cd4;cd3(30); // call M1, M2, M1, then M3cd3 -= cd1; // remove last M1cd3(40); // call M1, M2, then M3cd3 -= cd4;cd3(50); // call M1 then M2cd3 -= cd2;cd3(60); // call M1cd3 -= cd2; // impossible removal is benigncd3(60); // call M1cd3 -= cd1; // invocation list is empty// cd3(70); // System.NullReferenceException throwncd3 -= cd1; // impossible removal is benign}}As shown in the statement cd3 += cd1;, a delegate can be present in an invocation list multiple times. In thiscase, it is simply invoked once per occurrence. In an invocation list such as this, when that delegate is removed,the last occurrence in the invocation list is the one actually removed.Immediately prior to the execution of the final statement, cd3 -= cd1;, the delegate cd3 refers to an emptyinvocation list. Attempting to remove a delegate from an empty list (or to remove a non-existent delegate from anon-empty list) is not an error.The output produced is:Test.M1: -1Test.M2: -2Test.M1: 10Test.M2: 10Test.M1: 20Test.M2: 20Test.M1: 20300

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!