Saar Carmi

A .NET Blog

<August 2008>
SuMoTuWeThFrSa
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456


Navigation

Subscriptions

Post Categories



Determine whether someone is registered on event

A friend of mine asked me how would he determine whether a someone is registered on event of a another class.

If you want to check it from inside the class that defines the event, that's pretty easy - just check if the event field is not null.

But, if you want to do it from out side (without having the option to recompile the class that publishes the event),  the C# compiler does not let you compile that code. The only way I found to do it, is by using Reflection

Pay attention this is BAD CODING - you are not allowed to access private fields of other classes.

<code>
using System;
using System.Reflection;
using System.Windows.Forms;

public class A
{
 public event EventHandler MyEvent;
 public void AB()
 {
  if (MyEvent!= null) //compiles
  {}
 }

}

public class B
{
 public static void MyEventHandler (object source, EventArgs args)
 {}
 public static void Main()
 {
  A a = new A();
  //if (MyEvent!= null) //compilation error
 {}

  IsRegistered (a);
  
  a.MyEvent += new EventHandler (MyEventHandler);
  IsRegistered (a);
 }

 private static void IsRegistered (A a)
 {
  Type t = a.GetType();
  FieldInfo fld =t.GetField ("MyEvent", BindingFlags.NonPublic  | BindingFlags.Instance);
  System.Diagnostics.Debug.Assert (fld != null);
  
  Object o = fld.GetValue (a);
  System.Diagnostics.Debug.Assert (o != null);
  
  EventHandler eh = (EventHandler)o;
  if (eh == null)
  {
   Console.WriteLine ("no one is registerd");
  }
  else
  {
   Console.WriteLine ("still registered");
  }
 }
}


<code>

posted on Wednesday, December 22, 2004 9:01 AM by saarc





Powered by Dot Net Junkies, by Telligent Systems