C# 6.0 adds this new ?.
operator which now allows to invoke events like so:
someEvent?.Invoke(sender, args);
Now, from what I read, this operator guarantees that someEvent is evaluated once. Is it correct to use this kind of invocation instead of the classic pattern:
var copy = someEvent
if(copy != null)
copy(sender, args)
I'm aware of certain scenarios where above version of pattern would require additional locks, but let's assume the simplest case.
Yes
See Null-conditional Operators on MSDN.
There is an example covering what you ask
Without the null conditional operator
var handler = this.PropertyChanged;
if (handler != null)
handler(…)
With the null conditional operator
PropertyChanged?.Invoke(e)
The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only, keeping the result in temporary variable.
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