This question already has an answer here:
I am reading up iNotifyPropertyChanged in detail.
Can someone please clarify why do we need to check for
PropertyChanged !=null
?
Why would an event be null? Or in other words, why even check if it is null? The only time NotifyPropertyChanged
is called is when PropertyChanged
has been raised ( so it cannot be null), isn't it. Who/What can make it null?
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this,new PropertyChangedEventArgs(info));
}
}
Thank you.
If nobody has subscribed to the event it will be null. So, you'd get a NullReferenceException on the event at runtime if you didn't.
In the case of the interface you're talking about, its also likely the raising action will occur before the subscriber has a chance to subscribe albeit imminent they are going to subscribe because the INotifyPropertyChanged interface is quite chatty.
null
for a couple reasons. The first is because it can be null
. The second is because if that property were not used on the WPF component, but rather behind the scenes as support, then there would be no PropertyChanged
registrations. There are likely many other cases. Therefore, reason #1 is the reason you check for null
in every case. - Mike Perrenoud