Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we check PropertyChanged event for null value when implementing iNotifyPropertyChanged? [duplicate]

Tags:

c#

mvvm

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.

like image 398
iAteABug_And_iLiked_it Avatar asked Apr 19 '13 10:04

iAteABug_And_iLiked_it


People also ask

How PropertyChanged event works?

The PropertyChanged event can indicate all properties on the object have changed by using either null or String. Empty as the property name in the PropertyChangedEventArgs. Note that in a UWP application, String.

What is the purpose of INotifyPropertyChanged?

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. For example, consider a Person object with a property called FirstName .

How do you implement INotifyPropertyChanged?

To implement INotifyPropertyChanged you need to declare the PropertyChanged event and create the OnPropertyChanged method. Then for each property you want change notifications for, you call OnPropertyChanged whenever the property is updated.

What is INotifyPropertyChanged Xamarin?

The INotifyPropertyChanged changed interface is at the heart of XAML apps and has been a part of the . NET ecosystem since the early days of Windows Forms. The PropertyChanged event notifies the UI that a property in the binding source (usually the ViewModel) has changed. It allows the UI to update accordingly.


1 Answers

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.

like image 172
Mike Perrenoud Avatar answered Oct 03 '22 14:10

Mike Perrenoud