Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
From the author of

Using Subscription Methods for Events

Suppose that you are creating a custom component that contains a child, or constituent, component. Further, suppose that you want to surface an event on that constituent component. Intuitively, you might think that you could declare a new property whose type was a delegate and perform the assignments in the getter and setter of that property, as follows:

public EventHandler Click
{
 get{ return ConstituentControl.Click; }
 set{ ConsituentControl.Click += value; }
}

Aside from the fact that the code doesn't offer a means of removing a delegate form an invocation list (there is no -= operation), it is illegal code. You will get a compiler error that indicates that events (such as Click) can be used only on the left side of a += or -= operation. You might try to adjust the code and add the event keyword.

public event EventHandler FooClick
{
 get{ return ConsituentControl.Click; }
 set{ ConsituentControl.Click += value; }
}

Again, in addition to offering no way to remove a delegate, this code will cause an indistinctive and difficult-to-decipher "; expected" compiler error.

The solution is to use the add and remove accessor methods. Suppose that I have a UserControl with a PictureBox on it and want to permit consumers to assign an event handler to my UserControl's PictureBox's Click event directly. The solution is to surface the constituent PictureBox's Click event as an event in the containing UserControl:

// UserControl
public event EventHandler ClickPicture
{
 add
 {
  pictureBox1.Click += value;
 }
   
 remove
 {
  pictureBox1.Click -= value;
 }
}

To learn more about events and delegates in .NET, pick up a copy of my new book Visual Basic .NET Power Coding from Addison-Wesley (available July 2003, ISBN: 0672324075).

  • + Share This
  • 🔖 Save To Your Account