Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event handler and null-conditional operator [duplicate]

For example, implement INotifyPropertyChanged interface:

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    var handler = PropertyChanged;
    if (handler != null)
        handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Two things:

  1. Copy event to local variable to prevent errors with multithreading (here are some examples). Resharper gives notification, if you don't copy to local variable:

Possible NullReferenceException

  1. Check it for null, to prevent NullReferenceException

But now, we can use ?. operator for null-checking. And if I use it, Resharper is idle: No errors

So, question is: should I copy event ProperyChanged to local variable, if I use null-conditional operator?

like image 490
Backs Avatar asked May 20 '16 04:05

Backs


2 Answers

should I copy event ProperyChanged to local variable, if I use null-conditional operator?

No, there's no need. In fact, one of the main reasons the null-conditional operator was introduced was to simplify code using this pattern. It has the same effect as copying the source value to a local variable and inherently avoids the "check and use" concurrency trap that the "copy to local variable" technique is intended to address.

See related posts:
Invoking Events, h(args) vs EventName?.Invoke() (almost an exact duplicate…it does approach the question from a slightly different angle though)
Why should I check for null before I invoke the custom event?
Raising C# events with an extension method - is it bad?
Is there any reason to assign an event to a local variable before raising it?

like image 69
Peter Duniho Avatar answered Oct 16 '22 00:10

Peter Duniho


There is other way for null checking - simple assign delegate{} to your event, so it never be null

public event PropertyChangedEventHandler PropertyChanged = delegate{};
like image 34
nurkanat Avatar answered Oct 15 '22 22:10

nurkanat