Camel
Camel

Reputation:

C# Event Handlers

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

Upvotes: 9

Views: 5138

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1499900

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).

Upvotes: 18

incaunu
incaunu

Reputation: 1

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

Upvotes: 0

Brody
Brody

Reputation: 2074

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.

Upvotes: 0

Gishu
Gishu

Reputation: 136613

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.

Upvotes: 1

Related Questions