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?
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.
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).
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).
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