/* * A C# program that generates a custom event. * Modified from the .NET documentation * * Ben Bederson, February 20, 2002 */ using System; //Step 1. Class that defines data for the event // public class AlarmEventArgs : EventArgs { private int nrings = 0; // Constructor. public AlarmEventArgs(int nrings) { this.nrings = nrings; } // Properties. public int NumRings { get { return nrings; } } } //Step 2. Delegate declaration. // public delegate void AlarmEventHandler(object sender, AlarmEventArgs e); // Class definition. // public class AlarmClock { //Step 3. The Alarm event is defined using the event keyword. //The type of Alarm is AlarmEventHandler. public event AlarmEventHandler Alarm; // //Step 4. The protected OnAlarm method raises the event by invoking //the delegates. The sender is always this, the current instance of //the class. // protected virtual void OnAlarm(AlarmEventArgs e) { if (Alarm != null) { //Invokes the delegates. Alarm(this, e); } } public void ForceAlarm() { OnAlarm(new AlarmEventArgs(3)); } } public class Test { static public void Main() { new Test(); } public Test() { AlarmClock clock = new AlarmClock(); clock.Alarm += new AlarmEventHandler(alarmHandler); clock.ForceAlarm(); } void alarmHandler(object sender, AlarmEventArgs e) { Console.WriteLine("alarm! " + e.NumRings + " rings"); } }