Event Invocation, h (args) and EventName? .Invoke ()

I always triggered events like that

void onSomeEvent(string someArg) { var h = this.EventName; if (h != null) { h(this, new MyEventArgs(someArg)); } } 

Today, VS 2015 tells me that this can be simplified:

 MyEvent?.Invoke(this, new MyEventArgs(someArg)); 

A few questions on this last method that I have not seen before:

  • Supposedly ? after the event name is a check if the handler is null?
  • Assuming the handler is non-zero, .Invoke() seems simple enough
  • I have used the first example for many years and realized that it prevents race conditions ... presumably what ?.Invoke() second example does this too?
+7
c # events
source share
1 answer

Presumably? after the event name is a check, is the handler null?

Yes. This is the null operator introduced in C # 6. It is useful in all ways.

I have used the first example for many years and realized that it prevents race conditions ... presumably what ?.Invoke() second example does this too? (see question number 1)

Yes. In principle, they are equivalent. In particular, it does not evaluate the expression MyEvent twice. It evaluates it once, and then if the result is not zero, it invokes Invoke on it.

+7
source share

All Articles