5

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.


1 답변


9

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.


  • thank you for your answer:) - iAteABug_And_iLiked_it
  • @iAteABug_And_iLiked_it, no problem! I'm glad I could be of assistance! - Mike Perrenoud
  • who is the subscriber in this case ? I have never implemented a subscriber manually to hook that event with my own handler. in this case, I would assume it is WPF that does this, so if we know it is WPF doing this, why check Null ? - zheng yu
  • @zhengyu we check 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

Linked


Related

Latest