Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement INotifyPropertyChanged with nameof rather than magic strings?

I was reading about the new nameof keyword in C# 6. I want to know how can I implement INotifyPropertyChanged using this keyword, what are the prerequisites (of course other than C# 6) and how it will effect the performance of my MVVM application?

like image 269
Mehrad Avatar asked Dec 12 '14 11:12

Mehrad


3 Answers

It would look like this:

public string Foo
{
   get
   {
      return this.foo;
   }
   set
   {
       if (value != this.foo)
       {
          this.foo = value;
          OnPropertyChanged(nameof(Foo));
       }
   }
}

The nameof(Foo) will be substituted with the "Foo" string at compile time, so it should be very performant. This is not reflection.

like image 197
Wim Coenen Avatar answered Oct 21 '22 20:10

Wim Coenen


Here's a complete code sample of a class using the new C# 6.0 sugar:

public class ServerViewModel : INotifyPropertyChanged {
    private string _server;
    public string Server {
        get { return _server; }
        set {
            _server = value;
            OnPropertyChanged(nameof(Server));
        }
    }

    private int _port;
    public int Port {
        get { return _port; }
        set {
            _port = value;
            OnPropertyChanged(nameof(Port));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName) => 
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

With this, you get the nameof() operator, the null-conditional operator ?., and an expression-bodied function (the OnPropertyChanged definition).

like image 25
saluce Avatar answered Oct 21 '22 19:10

saluce


It's just a matter of using nameof() instead of the magic string. The example below is from my blog article on the subject:

private string currentTime;

public string CurrentTime
{
    get
    {
        return this.currentTime;
    }
    set
    {
        this.currentTime = value;
        this.OnPropertyChanged(nameof(CurrentTime));
    }
}

Since it is evaluated at compile-time, it is more performant than any of the current alternatives (which are also mentioned in the blog article).

like image 44
Gigi Avatar answered Oct 21 '22 20:10

Gigi