I have an abstract class A which has a required function for checking thresholds. When a threshold is violated I want an event raised that says notify me. I’ve done this sort of thing in Qt many times, but I can’t seem to figure out how to transfer this to C#. Here’s the structure I’ve currently got in mind.
namespace N
{
abstract class A
{
public delegate void Notify();
public event Notify Notifier;
public abstract void CheckThreshold();
}
class B : A
{
public override void CheckThreshold()
{
Notifier();
}
}
class N
{
public AlertMe()
{
}
public static Main()
{
var b = new B();
b.Notifier += new A.Notify(AlertMe);
b.CheckThreshold();
}
}
}
Typically the form you want to follow is this:
so in your case you probably want:
Now a few things – the EventHandler type is some nice syntactic sugar for making an event of a particular type. The lambda expression on the right initializes it to a default handler so you don’t have to check it for null before you invoke it.
EventArgs is event-specific information – you have none, but if you did you would subclass EventArgs and put in whatever data your event receivers would need.
The pattern of
public event SomeEventNameandprotected virtual void OnSomeEventpair is prescribed by Microsoft for events in .NET. You don’t have to follow this, but it’s what .NET programmers want.