Friday, March 30, 2007

Verifying event subscription

Avner Kashtan wrote a nice post about using reflection to verify you are subscribed to an event:

FieldInfo delegateField = myObj.GetType().GetField("MyEvent", BindingFlags.NonPublic BindingFlags.Instance);
EventHandler del = delegateField.GetValue(myObj) as EventHandler;

And once we had that - it's a simple matter of iterating the invocation list and seeing whether I've registered already:

foreach (EventHandler handler in del.GetInvocationList())
{
if (handler.Target == this)
return true;
}

Just be aware to the fact that using Obfuscation to protect your code will break this code.

No comments: