1 csharp comment // The Delegate declaration which defines the signature of methods which can be invoked
2 csharp code public delegate void ScoreChangeEventHandler (int newScore, ref bool cancel);
4 csharp comment // Class which makes the event
5 csharp code public class Game {
6 csharp comment // Note the use of the event keyword
7 csharp code public event ScoreChangeEventHandler ScoreChange;
11 csharp comment // Score Property
12 csharp code public int Score {
14 csharp code return score;
17 csharp code if (score != value) {
18 csharp code bool cancel = false;
19 csharp code ScoreChange (value, ref cancel);
20 csharp code if (! cancel)
21 csharp code score = value;
27 csharp comment // Class which handles the event
28 csharp code public class Referee
30 csharp code public Referee (Game game) {
31 csharp comment // Monitor when a score changes in the game
32 csharp code game.ScoreChange += new ScoreChangeEventHandler (game_ScoreChange);
35 csharp comment // Notice how this method signature matches the ScoreChangeEventHandler's signature
36 csharp code private void game_ScoreChange (int newScore, ref bool cancel) {
37 csharp code if (newScore < 100)
38 csharp code System.Console.WriteLine ("Good Score");
40 csharp code cancel = true;
41 csharp code System.Console.WriteLine ("No Score can be that high!");
46 csharp comment // Class to test it all
47 csharp code public class GameTest
49 csharp code public static void Main () {
50 csharp code Game game = new Game ();
51 csharp code Referee referee = new Referee (game);
52 csharp code game.Score = 70;
53 csharp code game.Score = 110;