Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to subscribe to event subscriptions in C#?

Tags:

c#

events

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;
like image 892
Lasse Christiansen Avatar asked May 07 '12 14:05

Lasse Christiansen


3 Answers

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.

like image 195
dtb Avatar answered Sep 30 '22 13:09

dtb


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.

like image 41
kfuglsang Avatar answered Sep 30 '22 14:09

kfuglsang


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.

like image 36
Tim Avatar answered Sep 30 '22 15:09

Tim