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?
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:
override one-or-more abstract membersinterface parameter that the consumer must supply If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With