Menu:

Recent Entries

Categories

Archives

Links

Blogs
- Dflying's Night
- David's Untitled Life
- Dflying's Blog in Chinese

This blog is hosted by DreamHost!

Syndicate

RSS 0.90
RSS 1.0
RSS 2.0
Atom 0.3

Prefer Overrides to Event Handlers in ASP.NET Page

Dflying | 29 March, 2006 06:43

First let’s take a look at two small pieces of code in an ASP.NET code file:

This one is the well known Page_Load() method. Actually it is an event handler which got executed when a Load Event defined in System.Web.UI.Page is fired.

// use event handler
protected void Page_Load(object sender, EventArgs e)
{
    // logic here
}

This one, the OnLoad() method just overrides its base method.

protected override void OnLoad(EventArgs e)
{
    // logic here
    base.OnLoad(e);
}

Though the two methods above can do the same things to initialize your ASP.NET page, I prefer the override way.


Firstly, Event mechanism is used for communicating between independent objects. For example, when a Button is clicked, a Page may get this information by listening its Click Event. But in this case, the Load Event is defined and fired in the Page’s base class - System.Web.UI.Page, which is also part of the object. So the behavior that one object fires an Event and handles in itself will be wired.

Then, Event is not as efficient as Override. The implementation of .NET Framework makes this and it is well known.

Still, if you decide to use event, you will have to write code in two places: one is to attach the event handler and the other is the handler body. (Though ASP.NET 2.0 provides some pre defined event handler names such as Page_Load and Page_Init, consider lots of people are still using ASP.NET 1.1) But you just need to write the override method if choosing the override way. That could be a little bit of simpler.

Event has its own advantages such as wire up at runtime and allow muti-cast. But in ASP.NET Pages we will never use these features. We will always write some code to init our page and we never write more than one Page_Load() methods.

A little extra work to do when using Override is remember to call the base method.

Posted in ASP.net. Comment: (0). Trackbacks:(198). Permalink
«Next post | Previous post»

Referers

Comments

Leave a Reply

Auth Image