Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforcing event handling wireup

Is there a way to perform compile time enforcement of event handling wireup?

So for example lets say I have a class that exposes the standard EventHandler<T> can I ensure that any instantiated instances of this class have the OnMyEvent handler, handled? (Preferably at compile time)

The only way I can see of performing this is through either having an eventhandler as part of the objects constructor or using reflection at runtime. Are there any alternatives?

Also, if C# doesn't allow for this functionality; out of curiosity do any other languages?

like image 372
Maxim Gershkovich Avatar asked May 31 '11 06:05

Maxim Gershkovich


1 Answers

Events are usually intended for optional consumption by the calling code of the object - for example, as an observer (or multiple observers). It is pretty rare that handling the event is enforced. There is no standard language / compiler construct for verifying an event gets subscribed at compile-time (and I suspect it would be very hard, since you could validly subscribe/unsubscribe at any time, at any place in the code - possibly multiple times, i.e. +HandlerA, +HandlerB, -HandlerA, -HandlerB - which ends with no subscribers).

In the scenario you present, where it is required, then passing it in to the constructor sounds more appropriate, but I would probably use Func<...> or Action<...> in this case (not EventHandler<T>). But that is subjective.

Other approaches:

  • make it an abstract class and force the consumer to subclass and override one-or-more abstract members
  • have an interface parameter that the consumer must supply
like image 134
Marc Gravell Avatar answered Oct 23 '22 12:10

Marc Gravell