Invoking Events, h(args) vs EventName?.Invoke()

I've always invoked events as so

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

Today VS 2015 tells me this can be simplified:

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

A few questions on this latter method, which I've not seen before:

  1. Presumably the ? after the event name is a check if the handler is null?
  2. Assuming the handler is not null, .Invoke() seems straightforward enough
  3. I've used the first example for years and realize it prevents race conditions... presumably the ?.Invoke() of the second example does so as well?
Jon Skeet
people
quotationmark

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

Yes. It's the null conditional operator, introduced in C# 6. It's useful in all kinds of ways.

I've used the first example for years and realize it prevents race conditions... presumably the ?.Invoke() of the second example does so as well? (see question #1)

Yes. Basically, they're equivalent. In particular, it does not evaluate the MyEvent expression twice. It evaluates it once, and then if the result is non-null, it calls Invoke on it.

people

See more on this question at Stackoverflow