Winforms subscribing to own events

One common thing I see developers doing in WinForms is forms/controls subscribing to their own events so you get

this.Load += new System.EventHandler(this.WelcomeQuickViewWF_Load);
this.Activated += new System.EventHandler(this.WelcomeQuickViewWF_Activated);

rather than

protected override void OnActivated(EventArgs e)
{
}

Now I know the second way is more Object Oriented, the first way is event driven and I tend to refactor towards overriding - is there any reason NOT to do this? What I don't want to be doing is making changes that are not really needed and purely an aesthetic choice.

Answers


By subscribing to your own event, you give up control over when your code is invoked when there are other subscribers to the event. By overriding the event raising method, you have full control over when your code should be invoked. You could invoke it before notifying subscribers or after. There's also no chance of your code being canceled on a cancelable event.

If the method is overridable, do so. Otherwise register as you have no other choice.


MSDN says that overriding the On* methods is the preferred technique for handling an event in a derived class:

The OnActivated method also allows derived classes to handle the event without attaching a delegate. Overriding this method is the preferred technique for handling the event in a derived class.

So I'd say the event handler approach is non-idiomatic.


Need Your Help

User32 API calls in .NET

.net managed user32

I'm currently planning out a project involving creating a shell replacement for Windows (based on Blackbox, bblean specifically). However I wish to leverage the power of .NET to do so. Many of th...