9

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?

Community
  • 1
  • 1
Backs
  • 24,430
  • 5
  • 58
  • 85

2 Answers2

11

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?

Community
  • 1
  • 1
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
1

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

public event PropertyChangedEventHandler PropertyChanged = delegate{};
nurkanat
  • 51
  • 4
  • 3
    Yes, I know about this solution, but I don't want to create new objects when it is not necessary – Backs May 20 '16 at 05:07