Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Events are assignable, like delegates
namespace AlarmNamespace
{
public class AlarmEventArgs : EventArgs
{
private DateTime alarmTime;
private bool snoozeOn = true;
public AlarmEventArgs (DateTime time)
{
this.alarmTime = time;
}
public DateTime Time
{
get { return this.alarmTime; }
}
public bool Snooze
{
get { return this.snoozeOn; }
set { this.snoozeOn = value; }
}
}
public class Alarm
{
private DateTime alarmTime;
private int interval = 10;
public delegate void AlarmEventHandler (object sender, AlarmEventArgs e);
public event AlarmEventHandler AlarmEvent;
public Alarm (DateTime time)
: this (time, 10)
{
}
public Alarm (DateTime time, int interval)
{
this.alarmTime = time;
this.interval = interval;
}
public void Set ()
{
while (true)
{
System.Threading.Thread.Sleep (100);
DateTime currentTime = DateTime.Now;
// Test whether it is time for the alarm to go off.
if (currentTime.Hour == alarmTime.Hour &&
currentTime.Minute == alarmTime.Minute)
{
AlarmEventArgs args = new AlarmEventArgs (currentTime);
OnAlarmEvent (args);
if (!args.Snooze)
return;
else
this.alarmTime = this.alarmTime.AddMinutes (this.interval);
}
}
}
protected void OnAlarmEvent (AlarmEventArgs e)
{
AlarmEvent (this, e);
}
static void Main ()
{
Alarm a = new Alarm (DateTime.Now.AddSeconds(1));
a.AlarmEvent += (o, e) => Console.WriteLine (1);
a.AlarmEvent += (o, e) => Console.WriteLine (2);
a.AlarmEvent = (o, e) => Console.WriteLine (3);
a.Set ();
Console.Read ();
}
}
}
@Chiel92

This comment has been minimized.

Copy link
Owner Author

commented Dec 17, 2015

Prints: 3.

@mpipalia

This comment has been minimized.

Copy link

commented Sep 1, 2016

For those who are wondering how this is possible, it is because the static Main method is inside the Alarm class, which has the event AlarmEvent. Code inside the Alarm class has full access to its own events, and can remove previously attached handlers as shown in the code above. A C# event provides protection outside of the class where it is declared, but gives you full control while inside the class. So, if you were to move the Main method to another class, you would get an error on the line with the WriteLine(3) method call.

@AdnanNazir

This comment has been minimized.

Copy link

commented Apr 3, 2017

@mpipalia !
So true, So great.
thanks for the help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.