SAMPLE CODE:
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
VS:
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String propertyName)
{
if (PropertyChanged!= null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Why is it that I always see people creating assigning PropertyChanged to a “handler” instead of just using it?
If you do it the simpler way, and a different thread removes the last handler from the event just inside your
if, you’ll get a null reference. (delegates are immutable)By making a
handlertemporary, you prevent this, since you only check the field once.If the event will never be unsubscribed to from multiple threads, you don’t need the temporary.