If I have an event like this:
public delegate void MyEventHandler(object sender, EventArgs e);
public event MyEventHandler MyEvent;
And adds an eventhandler like this:
MyEvent += MyEventHandlerMethod;
... is it then possible to register this somehow? In other words - is it possible to have something like:
MyEvent.OnSubscribe += MySubscriptionHandler;
Similar to auto-implemented properties, events are auto-implemented by default as well.
You can expand the declaration of an event
as follows:
public event MyEventHandler MyEvent
{
add
{
...
}
remove
{
...
}
}
See, for example, How to: Use a Dictionary to Store Event Instances (C# Programming Guide)
See Events get a little overhaul in C# 4, Part I: Locks for how auto-implemented events differ between C# 3 and C# 4.
It is possible to declare the event accessors specifically, i.e., the add and remove accessors.
Doing so makes it possible to do custom logic when new event handlers are added.
When you define your events, you can actually use the longer format to execute more code when people attach or remove themselves from your events.
Check out the info on the add and remove keywords.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With