C# How to find if an event is hooked up

If the object concerned has specified the event keyword, then the only things you can do are add (+=) and remove (-=) handlers, nothing more.

I believe that comparing the invocation list length would work, but you need to be operating inside the object to get at it.

Also, keep in mind that the += and -= operators return a new event object; they don’t modify an existing one.

Why do you want to know if a particular event is hooked up? Is it to avoid registering multiple times?

If so, the trick is to remove the handler first (-=) as removing a handler that’s not there is legal, and does nothing. Eg:

// Ensure we don't end up being triggered multiple times by the event
myObject.KeyEvent -= KeyEventHandler;
myObject.KeyEvent += KeyEventHandler;

Leave a Comment