Saar Carmi

A .NET Blog

<November 2008>
SuMoTuWeThFrSa
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456


Navigation

Subscriptions

Post Categories



Wednesday, December 22, 2004 - Posts

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 Wednesday, December 22, 2004 9:01 AM by saarc with 5 Comments




Powered by Dot Net Junkies, by Telligent Systems