Question

The boiler plate OnPropertyChanged code that you will likely see in almost any databinding example is as follows

public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{    
    PropertyChangedEventHandler handler = PropertyChanged;
    if(handler!=null)
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

Isn't this redundant though? Wouldn't it be easier to say this

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {    
         if(PropertyChanged!=null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

I am sure there is a reason why we do this I just can't find it.

No correct solution

OTHER TIPS

Using the second implementation it's possible for another thread to remove the only remaining event handler after the null check passes but before the delegate is invoked, resulting in a null referee exception. By copying the delegate before the check (delegates are immutable, removing a handler means assigning a new delegate, not mutating the existing one) means that such a NRE isn't possible. What is possible however is to invoke a handler after is has been removed, which can also cause problems.

If you know that the event will not have handlers added/removed from a thread other than the thread firing the event, then the two are equivalent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top