14.2 A first delegate example


Let's combine what we have done so far into a full concrete example. Study the program below.

 1:  using System;  2:  3:  delegate int MyDelegate (int i);  4:  5:  class TestClass{  6:  7:    static int Double (int val){  8:      Console.WriteLine("running Double");  9:      return val*2; 10:    } 11: 12:    int Triple (int val){ 13:      Console.WriteLine("running Triple"); 14:      return val*3; 15:    } 16: 17:    public static void Main(){ 18: 19:      TestClass tc = new TestClass(); 20:  MyDelegate d1, d2;  21: 22:  d1  =  new MyDelegate(TestClass.Double);  23:  d2  =  new MyDelegate(tc.Triple);  24: 25:      Console.WriteLine(  d1(3)  ); 26:      Console.WriteLine(" ---------- "); 27:      Console.WriteLine(  d2(5)  ); 28:    } 29:  } 

Output:

 c:\expt>test Running Double 6 ---------- Running Triple 15 

The MyDelegate type is declared on line 3 outside the scope of any class. MyDelegate is compatible with any method that returns an int , and takes in a single int as parameter. TestClass has two methods : a static Double , and a non-static Triple . Since both Double and Triple return an int , and take in a single int as parameter, both methods are compatible with the MyDelegate type. Two delegate instances of MyDelegate are created on lines 22 “ 23 “ d1 encapsulates the static method Double , while d2 encapsulates the instance method Triple .

On lines 25 and 27, both delegate instances are invoked with different int parameters. When d1 is invoked (line 25), the static method Double is invoked with 3 as the input parameter “ the value of 6 is returned and printed out. When d2 is invoked (line 27), the instance method Triple is invoked with the parameter 5 “ the value 15 is returned and printed out.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net