tags:

views:

2147

answers:

4
+5  Q: 

C# Event Handlers

How can I check in C# if button.Click event has any handlers associated? If (button.Click != null) throws compile error.

+13  A: 

You can't. Events just expose "add a handler" and "remove a handler" - that's all. (In fact in the CLR you can also have metadata to associate a method with "fire the event" but the C# compiler never generates that.) Some event publishers may offer additional means to check whether or not there are any subscribers (or indeed let you see those subscribers) but it's not part of the event pattern itself.

See my article about events for more information, or look at the "events" tag (which I'm about to add to this question).

Jon Skeet
+1  A: 

Why do you need this? What is the context? Maybe there's a better way to achieve the result
The button is an external object and what you're trying to do is check is its internal list of subscribers without asking it. It's violating encapsulation..
You should always let the object manage the subscribers for the events it exposes. If it wanted clients to be aware, it would have exposed a method HasClientsRegistered. Don't break in.

Gishu
A: 

I think you can if you are in the class that raises the event.

You can define the handler and enumerate each.

e.g. If your event is defined as

event System.EventHandler NewEvent;

Then on the raise event method you might create you can do...

    EventHandler handler = NewEvent;
    if(handler != null)
    {
      handler(this, e);
    }

That will give you the handler and from that you can get the Invocation List.

Brody
To check whether or not there are any subscribers, you just need "if (NewEvent != null)" - but this isn't really getting it from the event, it's getting it from the backing field. My answer assumes that the OP is interested in other events, given the "button.Click" example.
Jon Skeet
A: 

EventDescriptor e = TypeDescriptor.GetEvents(yourObject).Find("yourEventName", true);

incaunu