When implementing INotifyPropertyChanged
, should PropertyChanged
only be called when n != value
or should it be called because set has been called?
What I am looking for here is an industry standard recommendation (if such a thing exists) for which implementation is better and why.
Example 1 - illustrates a "dumb" event raising strategy
class Person : INotifyPropertyChanged
{
private string name;
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get
{
return name;
}
set
{
name = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
}
Use cases with Example 1
Person p = new Person();
p.Name = "John"; // ProperyChanged fired
p.Name = "John"; // ProperyChanged fired
Example 2 - illustrates a "clever" event raising strategy
class Person : INotifyPropertyChanged
{
private string name;
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get
{
return name;
}
set
{
if(name != value)
{
name = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
}
}
Use cases with Example 2
Person p = new Person();
p.Name = "John"; // ProperyChanged fired
p.Name = "John"; // ProperyChanged ignored as name == value
Notice if(name != value)
in Example 2, which would only allow a value change, and ProperyChanged
event when the incoming value does not match the existing value.