Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INotifyPropertyChanged Delegate

Tags:

c#

wpf

I saw a implementation of INotifyPropertyChanged like

public event PropertyChangedEventHandler PropertyChanged = delegate { };

I usually implement it like

protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

What is the difference/advantages / disadvantages between the 2 and what is recommended to use use?

like image 563
J_PT Avatar asked Jun 25 '26 15:06

J_PT


1 Answers

The difference is simply that by initializing PropertyChanged with a no-op delegate to start with, you don't need to worry about whether or not the delegate is null due to there being no subscribers.

Before C# 6, the "check whether or not it's null" aspect was a bit of a pain - with the null conditional operator that you're using, it's probably simpler to just use that to handle there being no subscribers. The other approach still works though, and you can even use them together - it'll just be redundant.

like image 100
Jon Skeet Avatar answered Jun 28 '26 05:06

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!