Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use null conditional operator instead of classic event raising pattern? [duplicate]

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.

like image 201
Grzegorz Sławecki Avatar asked Sep 23 '15 08:09

Grzegorz Sławecki


1 Answers

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.

like image 115
MyDaftQuestions Avatar answered Nov 15 '22 16:11

MyDaftQuestions