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:
NullReferenceException
But now, we can use ?.
operator for null-checking. And if I use it, Resharper is idle:
So, question is: should I copy event ProperyChanged
to local variable, if I use null-conditional operator?
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?
There is other way for null checking - simple assign delegate{} to your event, so it never be null
public event PropertyChangedEventHandler PropertyChanged = delegate{};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With