Share via


How check if Event handler is null

Question

Friday, November 11, 2005 4:39 AM

By example:

Page.Init += new System.EventHandler(Page_Init);

I cannot do this:

if (Page.Init != null)
{
   Page.Init += new System.EventHandler(Page_Init);
}

Why? If we use twice:
   Page.Init += new System.EventHandler(Page_Init);
   Page.Init += new System.EventHandler(Page_Init);
The event will be registered twice, then is necessary some method to check if the event is null (or the count of events registered).

Comments?

All replies (3)

Friday, November 11, 2005 7:55 AM

Page.Init already exists and you do not need to check for it, unless you are using some other class that does not derive from Page and you do not know.

this code though prevents wiring a null handler:

if (Page_Init != null){
   Page.Init += new System.EventHandler(Page_Init);
}

HTH!


Friday, November 11, 2005 12:20 PM

rmprimo

I have used the Page.Init only as example. My question is about all kinds of event handlers.

Your solution does not works because I need know about Page.Init object (what hold events references). I wish know if is null, or what are the events what are assigned in (because we can register multiple events handlers with += operator).

Thank you


Friday, November 11, 2005 4:40 PM

Ok.The Control.Init which the Page inherits is as good an example as any.
 
The event is not null. The author of the class should make sure of that.

Somewhere in the Control class there must be code for OnInit like this which invokes the event.

protected internal virtual void OnInit(EventArgs e) {
   if (this.Init != null)
      this.Init(e);
}

Invoking an event can only be done from within the class that declared the event. Derived classes cannot directly invoke events declared within the base class. They can, however, access the wrapper OnInit() and raise it, but as you can see the null is taken care of. If null it just won't fire.

So now your question boils down to hooking/unhooking multiple handlers.(+=. -=)

I think you want to know what all is hooked up at any one time. You are the one who has to implement this "minding" logic. For this there is a System.ComponentModel.EventHandlerList collection that is exposed as a property Control.Events. It is a linear list so perf may suffer if a lot of handlers are added but in the page scenario should be just fine.

Here are resources on that.

http://msdn.microsoft.com/en-us/library/system.web.ui.control.events

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconprovidingeventfunctionality.asp

HTH!