A type can declare that it handles some set of events raised by one of its data members. It does so by declaring the data member that raises the events with the WithEvents
modifier. This causes the data member to be renamed with a leading underscore and replaced with a property of the same name. If the data member's name is F
, then it is renamed to _F
and a property F
is implicitly declared. If there is a collision between the data member's new name and another declaration, an error will be reported.
The implicit property takes care of hooking and unhooking the relevant event handlers. When a value is assigned to the data member, the property first calls the remove
method for the event on the instance currently in the variable (unhooking the existing event handler, if any). Then the assignment is made, and the property calls the add
method for the event on the new instance in the variable (hooking up the new event handler).
If a type declares a data member as WithEvents
, all events raised by that data member must be handled within the type itself. It is not possible in a derived type to handle events not handled by a base type on an inherited WithEvents
data member.