Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter code to trigger property changed events

Tags:

c#

wpf

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.

like image 466
JME Avatar asked Nov 10 '15 03:11

JME


2 Answers

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"));
like image 112
dxiv Avatar answered Oct 12 '22 22:10

dxiv


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.

like image 35
Enigmativity Avatar answered Oct 13 '22 00:10

Enigmativity