Being accustomed to VB.NET, I’m used to “just raise events”. Sure, custom events differ, but with “regular” events – I don’t need to check if the delegate is Nothing before raising.
With C#, I find myself repeating this pattern:
if (myHandler != null)
{
myHandler(this, new EventArgs());
}
I was thinking that the following pattern might prove more elegant:
- myHandler is initialized with an empty lambda:
myHandler = (sender, e) => { }; - myHandler is expected never to be null, so raising would simply become:
myHandler(this, new EventArgs());
Would this pattern be more or less performant than the previous one?
Are there other significant considerations I should take into account?
I think that the performance difference between the two approaches isn’t big enough to be relevant. If anything, I would argue that a null-check is cheaper than invoking a method through a delegate, even if it’s a no-op.
When talking about elegance, it should be pointed out that the
RaiseEventkeyword in VB.NET is automatically expanded by the compiler to exact same construct that you have to write yourself in C#:If you want to avoid repeating that construct throughout your code, you could encapsulate it in a couple of extension methods:
That way you can simply say:
which is semantically equivalent to the style used in VB.NET.