Replace the original TimesUp
event statement with the following statement, which uses the AlarmClockEventHandler
class:
//---public event EventHandler TimesUp;---
public event AlarmClockEventHandler TimesUp;
Add a Message
property to the class so that users of this class can set a message that will be returned by the event when the time is up:
public string Message { get; set; }
Modify the onTimesUp
virtual method by changing its parameter type to the new AlarmClockEventArgs
class:
if (TimesUp != null) TimesUp(this, e);
}
Finally, modify the t_Elapsed
event handler so that when you now call the onTimesUp()
method, you pass in an instance of the AlarmClockEventArgs
class containing the message you want to pass back to the event handler:
void t_Elapsed(object sender, ElapsedEventArgs e) {
if (DateTime.Now >= this.AlarmTime) {
t.Stop();
}
}
Here's the complete program: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
class AlarmClock {
Timer t;
if (TimesUp != null) TimesUp(this, e);
}
public DateTime AlarmTime { get; set; }
public AlarmClock() {
t = new Timer(100);
t.Elapsed += new ElapsedEventHandler(t_Elapsed);
}
public void Start() {
t.Start();
}
void t_Elapsed(object sender, ElapsedEventArgs e) {
if (DateTime.Now >= this.AlarmTime) {
t.Stop();
}
}
}
With the modified AlarmClock
class, your program will now look like this:
namespace Events {
class Program {
static void Main(string[] args) {
AlarmClock c = new AlarmClock() {
//---alarm to sound off at 16 May 08, 9.50am---
};
c.TimesUp += new AlarmClockEventHandler(c_TimesUp);
c.Start();
Console.ReadLine();
}
}
}
Figure 7-10 shows the output when the AlarmClock
fires the TimesUp
event.

Figure 7-10
Summary
This chapter discussed what delegates are and how you can use them to invoke other functions, as well as how you can use delegates to implement callbacks so that your application is more efficient and responsive. One direct application of delegates is events, which make GUI operating systems such as Windows possible. One important difference between delegates and events is that you cannot assign a delegate to an event by using the =
operator.