The saying goes "you learn something new every day", and today is no
exception. I'm not sure how I missed this, but never less, this
post shows how to gain finer control over adding and removing of event
handlers to public multicast delegate events.
Typically, most C# developers are used writing event code as follows:
The above code exposes a public multicast delegate event, which client callers subscribe to by adding handlers using the
+=
operator. However, it is possible to define a multicast delegate
event as a property, where the developer can control the adding and
removal of event handlers with add and remove accessor
decelerations.
The example below defines properties for each event, and the accessor
decelerations on each property manages the storage of event handlers
using a private hash table. This approach is usually undertaken when a
class defines many events, where the developer expects most of the
events to be unimplemented, thus saving some overhead in creating
multicast delegate event instances that are never assigned a handler.