Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

...jects\CSharpNutshell\Delegates_01_01_Introduction\Program.

cs
1 // A delegate type declaration is like an abstract method declaration,
2 // prefixed with the delegate keyword.
3
4 using System;
5
6 namespace Delegates_01_01_Introduction
7 {
8
// Define delegate type
9
delegate int Transformer(int x);
10
11
class Program
{
12
static void Main(string[] args)
13
{
14
// Create delegate instance
15
Transformer t;
16
17
18
// Assign method to delegate and invoke delegate
19
t = new Transformer(Square);
20
int result1 = t.Invoke(3);
21
22
// Assign method to delegate and invoke delegate (shorthand)
23
t = Cube;
int result2 = t(3);
24
25
Console.WriteLine(result1);
// 9
26
Console.WriteLine(result2);
// 27
27
}
28
29
30
// Define target method
31
static int Square(int x)
{
32
return x * x;
33
}
34
35
// Define target method
36
static int Cube(int x)
37
{
38
39
return x * x * x;
}
40
}
41
42 }
43

You might also like