5

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.

Ankur
  • 5,086
  • 19
  • 37
  • 62
iAteABug_And_iLiked_it
  • 3,725
  • 9
  • 36
  • 75

1 Answers1

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.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
  • @iAteABug_And_iLiked_it, no problem! I'm glad I could be of assistance! – Mike Perrenoud Apr 19 '13 at 10:51
  • 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 Mar 26 '18 at 13:54
  • @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 Mar 26 '18 at 14:11