Event handler and null condition statement

For example, we implement the 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:

  • Copy the event to a local variable to prevent multithreading errors ( here are some examples). Resharper issues a notification if you do not copy the local variable:

Possible NullReferenceException

  1. Check it for null to prevent a NullReferenceException

But now we can use the ?. Operator ?. for zero check. And if I use it, Resharper is idle: No mistakes

So the question is: should I copy the ProperyChanged event to a local variable if I use a null condition statement?

+6
source share
2 answers

should I copy the ProperyChanged event to a local variable if I use a null condition statement?

No, no need. In fact, one of the main reasons why the operator with the zero condition was introduced was to simplify the code using this template. It has the same effect as copying the original value to a local variable and essentially avoids the "check and use" concurrency trap, for which the "copy to local variable" method is intended.

See related posts:
Event call, h (args) and EventName? .Invoke () (almost exact duplicate & hellip; it approaches the question from a slightly different angle)
Why should I check for null before I trigger a custom event?
Raise C # events using extension method - is that bad?
Is there a reason to assign an event to a local variable before raising it?

+8
source

There is another way to check for zero - just assign the delegate {} to your event, so it will never be zero

 public event PropertyChangedEventHandler PropertyChanged = delegate{}; 
+1
source

All Articles