Reputation: 10325
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;
Upvotes: 6
Views: 235
Reputation: 62265
It's possible if you declare your custom event, like this pseudocode:
class MyClass
{
public event EventHandler MyEvent
{
add { //someone subscribed to this event ! }
remove { //someone unsubscribed from this event ! }
}
...
}
Upvotes: 1
Reputation: 6326
I guess, you are looking for event accessors. Way to customizing the references to the subscribers. Here is how you can do it
public class TestClass
{
private event EventHandler UnderlyingEvent;
public event EventHandler TestEvent
{
add
{
UnderlyingEvent += value;
}
remove
{
UnderlyingEvent -= value;
}
}
}
For more information, please visit this article
http://msdn.microsoft.com/en-us/magazine/cc163533.aspx
Upvotes: 1
Reputation: 15247
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.
Upvotes: 1
Reputation: 217411
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.
Upvotes: 11
Reputation: 2505
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.
Upvotes: 6