Removing and adding event handlers using reflection

Recently I ran into an situation that I need to remove all the event handlers, perform some work and then re-attach all the event handlers.  This requires using reflection since we need to discover the event handler in runtime. This is useful in cases where the object itself do not have knowledge of who has attached to itself. 

The code is listed just below.  We need the FieldInfo so that we can call GetValue() to get a reference to the event delegate.  Then using EventInfo.RemoveEventHandler() and EventInfo.AddEventHandler() to detach and re-attach the handler:

// define the binding flags for reflection
var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

// Target has a event call PropertyChanged
Type type = target.GetType();
var fieldInfo = type.GetField("PropertyChanged", bindingFlags);
var eventInfo = type.GetEvent("PropertyChanged", bindingFlags);

// using GetValue() to get the reference of event delegate
var del = fieldInfo.GetValue(target) as Delegate;

// detach the event handler
if (del != null)
  eventInfo.RemoveEventHandler(target, del);

// Do you thing here!!

// re-attach the event handler
if (del != null)
  eventInfo.AddEventHandler(target, del);

Simple enough?  We can further improve this by looping through all the events and fields, so we don’t need the hardcoded event name in string.

By Raymond Tsang

Tagged with: ,
Posted in C# Programming
2 comments on “Removing and adding event handlers using reflection
  1. Jonathan says:

    Who would have thought your post would have helped someone four years after you posted it. I just implemented this trick to work around a bug in a framework I am using.

  2. dbardi says:

    How would this work for an event on a static method?

Leave a Reply