Form Events: To Override or add event?

Nerseus

Danner
Joined
Oct 22, 2002
Messages
2,547
Location
Arizona, USA
I'm wondering if anyone's 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 class's 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 we've always used the event handler method, mostly because it's easier but somewhat out of ignorance (we had a lot of developers coding who didn't know you could use the override OnLoad).

With hiring some new people I'm in the process of reviewing our coding standards document and wanted to get some outside opinions. Maybe Microsoft has recommended a certain method? Maybe it's like variable naming - just pick a standard and use it consistently? Or maybe there's something we're 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 don't 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 class's method). You are the form, so it's only right that your event method gets called by the framework directly. If you do this by way of attaching an event handler, it's as though you're an outsider who just happens to be interested in one of the form's events. (This would be like, for example, when you attach an event handler to a Button member's 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, you'll 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