I think the performance difference between the two approaches is not so great as to be relevant. Anyway, I would say that a zero check is cheaper than calling a method through a delegate, even if it does not work.
Speaking of elegance , it should be pointed out that the RaiseEvent keyword in VB.NET automatically expands the compiler to the exact same design that you should write yourself in C #:
If (Not MyEvent Is Nothing) Then MyEvent.Invoke(New EventArgs()) End If
If you want to avoid repeating this construct in all your code, you can encapsulate it in several extension ways:
public static void RaiseEvent(this EventHandler source, object sender) { if (source != null) { source.Invoke(sender, new EventArgs()); } } public static void RaiseEvent<T>(this EventHandler<T> source, object sender, T eventArgs) where T : EventArgs { if (source != null) { source.Invoke(sender, eventArgs); } }
So you can just say:
myEvent.RaiseEvent(this); myOtherEvent.RaiseEvent(this, new SomeEventArgs());
which is semantically equivalent to the style used in VB.NET.
source share