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?
In C# 6.0 there's no need to go to any of these lengths to do the null check, thanks to the conditional null operator
?.
The docs explain that calling
MyEvent?.Invoke(...)
copies the event to a temporary variable, performs the null check, and if not null, callsInvoke
on the temporary copy. This isn't necessarily thread-safe in every sense, as someone could have added a new event after the copy to the temporary variable, which wouldn't be called. It does guarantee you won't callInvoke
on null though.In short:
This is a bad idea in that the code which is consuming the event now has an expectation that the object with the event has been coded with an action by default. If your code is never going to be used anywhere else by anyone else then I guess you can get away with it.