C# How to find if an event is hooked up

Posted by Nick on Stack Overflow See other posts from Stack Overflow or by Nick
Published on 2009-07-15T05:16:42Z Indexed on 2010/04/14 15:13 UTC
Read the original article Hit count: 532

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about eventhandler