Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INotifyProperyChanged - why the extra assignment?

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));
    }
}
like image 576
Per Avatar asked Apr 03 '12 06:04

Per


1 Answers

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; 
like image 109
ahawker Avatar answered Sep 23 '22 02:09

ahawker