I've always invoked events as so
void onSomeEvent(string someArg) {
var h = this.EventName;
if (h != null) {
h(this, new MyEventArgs(someArg));
}
}
Today VS 2015 tells me this can be simplified:
MyEvent?.Invoke(this, new MyEventArgs(someArg));
A few questions on this latter method, which I've not seen before:
?
after the event name is a check if the handler is null?.Invoke()
seems straightforward enough?.Invoke()
of the second example does so as well? Presumably the ? after the event name is a check if the handler is null?
Yes. It's the null conditional operator, introduced in C# 6. It's useful in all kinds of ways.
I've used the first example for years and realize it prevents race conditions... presumably the
?.Invoke()
of the second example does so as well? (see question #1)
Yes. Basically, they're equivalent. In particular, it does not evaluate the MyEvent
expression twice. It evaluates it once, and then if the result is non-null, it calls Invoke
on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With