How do I get the subscribers of an event?

If the event is one published by another class, you can't - at least, not reliably. While we often think of an event as being just a delegate variable, it's actually just a pair of methods: add and remove (or subscribe and unsubscribe).

If it's your own code that's publishing the event, it's easy - you can make the add/remove accessors do whatever you like.

Have a look at my article on events and see if that helps you. If not, please give more details about what you want to do, specifying which bits of code you're able to modify and which you aren't.


In case you need to examine subscribers of an external class' event:

EventHandler e = typeof(ExternalClass)
    .GetField(nameof(ExternalClass.Event), BindingFlags.Instance | BindingFlags.NonPublic)
    .GetValue(instanceOfExternalClass) as EventHandler;
if (e != null)
{
    Delegate[] subscribers = e.GetInvocationList();
}

C# events/delegates are multicast, so the delegate is itself a list. From within the class, to get individual callers, you can use:

if (field != null) 
{ 
    // or the event-name for field-like events
    // or your own event-type in place of EventHandler
    foreach(EventHandler subscriber in field.GetInvocationList())
    {
        // etc
    }
}

However, to assign all at once, just use += or direct assignment:

SomeType other = ...
other.SomeEvent += localEvent;

Tags:

C#

Events