I want to be able to find out if an event is hooked up or not. I’ve looked around, but I’ve only found solutions that involved modifying the internals of the object that contains the event. I don’t want to do this.
Here is some test code that I thought would work:
// Create a new event handler that takes in the function I want to execute when the event fires
EventHandler myEventHandler = new EventHandler(myObject_SomeEvent);
// Get "p1" number events that got hooked up to myEventHandler
int p1 = myEventHandler.GetInvocationList().Length;
// Now actually hook an event up
myObject.SomeEvent += m_myEventHandler;
// Re check "p2" number of events hooked up to myEventHandler
int p2 = myEventHandler.GetInvocationList().Length;
Unfort the above is dead wrong. I thought that somehow the “invocationList” in myEventHandler would automatically get updated when I hooked an event to it. But no, this is not the case. The length of this always comes back as one.
Is there anyway to determine this from outside the object that contains the event?
There is a subtle illusion presented by the C#
eventkeyword and that is that an event has an invocation list.If you declare the event using the C#
eventkeyword, the compiler will generate a private delegate in your class, and manage it for you. Whenever you subscribe to the event, the compiler-generatedaddmethod is invoked, which appends the event handler to the delegate’s invocation list. There is no explicit invocation list for the event.Thus, the only way to get at the delegate’s invocation list is to preferably:
Here is an example demonstrating the latter technique.