The problem
Invoking event handlers in C# has always been a bit of a pain, because an event with no subscribers is usually represented as a null reference. This leads to code like this:
It’s important to use the handler
local variable, as if instead you access the field twice, it’s possible that the last subscriber will unsubscribe between the check and the invocation:
Now this can be simplified slightly using an extension method:
Then in each event, you can write a single line:
However, this means having a different extension method for each delegate type. It’s not too bad if you’re using EventHandler
but it’s still not ideal.
C# 6 to the rescue!
The null-conditional operator (?.
) in C# 6 isn’t just for properties. It can also be used for method calls. The compiler does the right thing (evaluating the expression only once) so you can do…