Form Events: To Override or add event?

Nerseus

Danner
Joined
Oct 22, 2002
Messages
2,547
Location
Arizona, USA
User Rank
*Expert*
Im wondering if anyones seen any reason why overriding an event on a form is better/worse than adding an event handler. Not counting the overhead of calling the base classs event and not counting the slight overhead of adding an event handler...

For example, to use the Form_Load event, you can use:
C#:
// In InitializeComponent
this.Load += new System.EventHandler(this.Form1_Load);

// Farther down, the actual function:
private void Form1_Load(object sender, System.EventArgs e)
{
    // Do something here
}

or you could use:
C#:
protected override void OnLoad(System.EventArgs e)
{
    // Do something here

    // Finally, call base class
    base.OnLoad(e);
}

At my company weve always used the event handler method, mostly because its easier but somewhat out of ignorance (we had a lot of developers coding who didnt know you could use the override OnLoad).

With hiring some new people Im in the process of reviewing our coding standards document and wanted to get some outside opinions. Maybe Microsoft has recommended a certain method? Maybe its like variable naming - just pick a standard and use it consistently? Or maybe theres something were missing...?


Thanks all!
-Nerseus
 
I use event handlers, because you have more control; you can remove/add the event handlers at runtime, and change their names if you want from OnWhatever if you want.
 
When you are writing custom controls the recommended method is to override (calling the base of course); however, I dont think there is a recommended method for just writing code for a form. Personally I use the events.
 
I would always handle a form event by way of overriding the event method (and calling the base classs method). You are the form, so its only right that your event method gets called by the framework directly. If you do this by way of attaching an event handler, its as though youre an outsider who just happens to be interested in one of the forms events. (This would be like, for example, when you attach an event handler to a Button members Click event. You are not the button itself; you are just interested in when something happens to the button.)

If you look at the documentation for any form event method, youll see the following text:

The OnBlah method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class.
 
Back
Top