Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
From the author of

Defining Subscription Methods

There is some additional information you can supply when defining an event. You can define add and remove accessor blocks to an event declaration, much like you would add get and set blocks to a property declaration. What's strange is that these methods are hardly mentioned in the help. Here is an example of an event named MyClick that shows the appropriate syntax for add and remove blocks.

public event EventHandler MyClick
{
 add
 {
  Debug.WriteLine("add called");
  Click += value;
 }
   
 remove
 {
  Debug.WriteLine("remove called");
  Click -= value;
 }
}

With our new definition, when you assign an event handler to MyClick using += then our add accessor method—represented by the add block—is called, and when you remove an event handler using -= the remove block is called. Oddly enough, unlike get and set, which get a blue syntax designating those two words as keywords, add and remove remain as plain old black text. Add and remove don't seem to be reserved words. "Curiouser and curiouser."

Again, although I will admit to not reading enough news groups when I am finishing up a book and as a result end up being a bit myopic about new developments, I haven't heard much about these two code blocks. In fact, the only help information I could discover was in the System.Reflection.Emit namespace. The EventBuilder, which is used to emit events as MSIL (Microsoft Intermediate Language) to an assembly, contains the two methods SetAddOnmethod and SetRemoveOnMethod. The help for SetAddOnMethod and SetRemoveOnMethod, which will emit these blocks as MSIL, indicates that add and remove are used to subscribe and unsubscribe to a particular event. I will give you a clue about how I have used them so far.

  • + Share This
  • 🔖 Save To Your Account