Wednesday, November 12, 2008

A Winforms-control should not subscribe to its own events

Each Winforms-control defines many events that can be used to receive all kinds of notifications. Often I see that a control subscribes to its own events, for example:

   1: // this code is added by the designer in the InitializeComponent() method
   2: this.Load += new System.EventHandler(this.Form1_Load);
   4: private void Form1_Load(object sender, EventArgs e)
   5: {
   6:     ...
   7: }

This will work OK, but events are conceptually not so simple. They are needed when you need a loose coupling between the publisher and the subscriber. This makes no sense if the publisher and the subscriber are the same control.

There is an alternative that is much simpler: for each event, there is also a virtual method that can be overridden:

   1: protected override void OnLoad(EventArgs e)
   2: {
   3:     base.OnLoad(e);
   5:     ...
   6: }

This alternative will also have a slightly better performance. However, you should not forget to call the base-implementation (luckily, this call will be added automatically by IntelliSense). The base-implementation will raise the event, so if you omit this then the other parts of the code will not receive this event from your control.

No comments: