Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

events

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?
like image 596
jleach Avatar asked May 06 '16 15:05

jleach


1 Answers

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.

like image 54
Jon Skeet Avatar answered Sep 28 '22 22:09

Jon Skeet