Initial Revision
[ohcount] / test / src_dir / cs1.cs
1 // The Delegate declaration which defines the signature of methods which can be invoked
2 public delegate void ScoreChangeEventHandler (int newScore, ref bool cancel);
3
4 // Class which makes the event
5 public class Game {
6     // Note the use of the event keyword
7     public event ScoreChangeEventHandler ScoreChange;
8
9     int score;
10
11         // Score Property
12     public int Score {
13         get {
14             return score;
15             }
16         set {
17             if (score != value) {
18                 bool cancel = false;
19                 ScoreChange (value, ref cancel);
20                 if (! cancel)
21                     score = value;
22             }
23         }
24     }
25 }
26
27 // Class which handles the event
28 public class Referee
29 {
30     public Referee (Game game) {
31         // Monitor when a score changes in the game
32         game.ScoreChange += new ScoreChangeEventHandler (game_ScoreChange);
33     }
34
35     // Notice how this method signature matches the ScoreChangeEventHandler's signature
36     private void game_ScoreChange (int newScore, ref bool cancel) {
37         if (newScore < 100)
38             System.Console.WriteLine ("Good Score");
39         else {
40             cancel = true;
41             System.Console.WriteLine ("No Score can be that high!");
42         }
43     }
44 }
45
46 // Class to test it all
47 public class GameTest
48 {
49     public static void Main () {
50         Game game = new Game ();
51         Referee referee = new Referee (game);
52         game.Score = 70;
53         game.Score = 110;
54     }
55 }