When implementing the INotifyPropertyChanged
interface in its most basic form, most people seem to implement it like this::
public virtual void OnPropertyChanged(string propertyName)
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
My question is: Why the extra assignment of var propertyChanged = PropertyChanged;
? Is it just a matter of preference, or is there a good reason for it? Surely the following is just as valid?
public virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
The assignment to a temporary variable removes the chance of a race condition between the null check and the last event subscriber, unsubscribing. See the .NET Event Guidelines here.
Snip:
// Make a temporary copy of the event to avoid possibility of
// a race condition if the last subscriber unsubscribes
// immediately after the null check and before the event is raised.
EventHandler<CustomEventArgs> handler = RaiseCustomEvent;
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