8

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.

Community
  • 1
  • 1
Grzegorz Sławecki
  • 1,727
  • 14
  • 27
  • 2
    Yes. And there's a blog post by Jon Skeet about doing just that. – i3arnon Sep 23 '15 at 08:08
  • 1
    It's actually a set of operators: `?.`, `?[`. – Paulo Morgado Sep 23 '15 at 10:54
  • @Paulo Morgado, I did correct it in the question, however I've found in Linqpad5 syntax tree view, that it's single `?` that gets parsed as an operator token, the following `[0]` is parsed as `SingleMemberAccessExpression, or some other expression in case of `.` access. – Grzegorz Sławecki Sep 24 '15 at 09:38
  • @GrzegorzSławecki and that all forms a `ConditionalAccessExpression`, right? IT might be more of a philosophical discussion, but that's what the documentation for the language (not the compiler) says. – Paulo Morgado Sep 24 '15 at 10:51
  • @Paulo Morgado, I agree that this is just a philosophical discussion and that's true that the documentation says that. I'm just wondering why. My reasoning is that if `?[` is an operator, then how would we call corresponding `]`. – Grzegorz Sławecki Sep 24 '15 at 11:20
  • @GrzegorzSławecki I think you are mixing operators with expressions. There is no mention of operators in the expression trees. – Paulo Morgado Sep 24 '15 at 15:06

1 Answers1

12

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.

MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120