Create empty C# event handlers automatically

Posted by TomA on Stack Overflow See other posts from Stack Overflow or by TomA
Published on 2008-12-04T13:41:28Z Indexed on 2010/03/24 19:23 UTC
Read the original article Hit count: 177

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about events