O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required