I have a class with tens of properties that need to raise property changed events, currently my code looks something like
public class Ethernet : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string timeStamp;
public string TimeStamp
{
get { return timeStamp; }
set
{
timeStamp = value;
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("TimeStamp"));
}
}
}
Is there a shorter way in C# to write this sort of code, I am doing excessive copy/paste operations for each property and I feel there must be a better way.
The quoted code is not thread safe as written. See Pattern for implementing INotifyPropertyChanged? why the code below is better, and the link to Eric Lippert's blog in the accepted reply why the story doesn't end there.
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs("TimeStamp"));
For answers to the actual question, see Implementing INotifyPropertyChanged - does a better way exist? including this C# 6.0 shortcut.
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TimeStamp"));
Do take a look at this answer: https://stackoverflow.com/a/2339904/259769
My code in provides and extension method to replace much of the setting code and let's you shorten your code to this:
public class Ethernet : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string timeStamp;
public string TimeStamp
{
get { return timeStamp; }
set { this.NotifySetProperty(ref timeStamp, value, () => this.TimeStamp); }
}
}
The other distinct advantage with this code is that it immediately becomes strongly-typed against the name of the property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With