Create empty C# event handlers automatically
- by TomA
It is not possible to fire an event in C# that has no handlers attached to it. So before each call it is necessary to check if the event is null.
if ( MyEvent != null ) {
MyEvent( param1, param2 );
}
I would like to keep my code as clean as possible and get rid of those null checks. I don't think it will affect performance very much, at least not in my case.
MyEvent( param1, param2 );
Right now I solve this by adding an empty inline handler to each event manually. This is error prone, since I need to remember to do that etc.
void Initialize() {
MyEvent += new MyEvent( (p1,p2) => { } );
}
Is there a way to generate empty handlers for all events of a given class automatically using reflection and some CLR magic?