Can I use a null conditional operator in place of the classic event raising pattern?

C # 6.0 adds a new operator ?. , which now allows triggering such events:

 someEvent?.Invoke(sender, args); 

Now, from what I read, this statement ensures that someEvent is evaluated once. Is it correct to use this type of call instead of the classic template:

 var copy = someEvent if(copy != null) copy(sender, args) 

I know certain scenarios where the above version of the template will require additional locks, but the simplest case is permissible.

+5
source share
1 answer

Yes

See Zero Conditional Statements on MSDN .

There is an example covering what you ask

Without a null conditional operator

 var handler = this.PropertyChanged; if (handler != null) handler(…) 

With a null conditional operator

 PropertyChanged?.Invoke(e) 

The new method is thread safe, because the compiler generates code for evaluating PropertyChanged only once, storing the result in a temporary variable.

+9
source

Source: https://habr.com/ru/post/1232076/


All Articles