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 ...
Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.