views:

68

answers:

2

Hi All,

How to know how many event handlers for an event?

I want a way to execute the following code:

// if (control.CheckedChanged.Handlers.Length == 0)
{
    control.CheckedChanged += (s, e) =>
    {
      // code;
    }
}

Note: this code is out side the control class.

Thanks in advance.

+3  A: 

You can't, because only the type that exposes the event has access to the actual delegate. From within the control, you could do something like that:

if (MyEvent!= null)
{
    EventHandler[] handlers = (EventHandler[])MyEvent.GetInvocationList();
    foreach(EventHandler handler in handlers)
    {
        ...
    }
}

Or, for what you're trying to do:

if (CheckedChanged == null)
{
    CheckedChanged += (s, e) =>
    {
      // code;
    }
}
Thomas Levesque
That code will always either throw a NullReferenceException or go into the `if` block... there's no such thing as a delegate instance with no actions.
Jon Skeet
@Jon, good point... I'll fix it
Thomas Levesque
@Thomas Levesque: This code works only if It wrote inside the class, but I'm talking about join an event to an event handler outside the class, so.. this solution didn't work for the second situation
Homam
As I said, there is no way to do it from outside the class (unless you're willing to use reflection on private members, which is quite ugly...)
Thomas Levesque
@Thomas, I'll add a flag property in the class "HasEventHandler" if there's no way.Thanks.
Homam
A: 

My answer is more of a comment for Thomas Levesque, but I can't comment yet, so here goes nothing. I find this area of C# a little ugly, since there's a possibility to introduce race conditions - i.e. different threads may race and you may enter the if statement with CheckedChanged != null

if (CheckedChanged == null)
{
    CheckedChanged += (s, e) =>
    {
      // code;
    }
}

You should either lock this code, but in many cases you will find yourself writing code like this

//Invoke SomeEvent if there are any handlers  attached to it.
if(SomeEvent != null) SomeEvent(); 

But SomeEvent may be nulled in the process, so it would be safer to write something like this

SomeEVentHandler handler = SomeEvent;
if (handler != null) handler();

...just to be extra safe.

Gleno