With the advent of .NET 4.5.3, WPF developers now have three (or more) ways to notify the INotifyPropertyChanged
Interface of property changes. Basically, my question is Which of the two methods introduced from.NET 4.5 onwards is the more efficient way to notify property changes and whether either way has any benefit when being used in WPF?
Background
For those not so familiar with this subject, here are the main three methods. The first is the original, more error prone method of simply passing a string:
public string TestValue
{
get { return testValue; }
set { testValue = value; NotifyPropertyChanged("TestValue"); }
}
protected virtual void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
The second method was introduced in .NET 4.5; the CallerMemberNameAttribute
:
public string TestValue
{
get { return testValue; }
set { testValue = value; NotifyPropertyChanged(); }
}
protected virtual void NotifyPropertyChanged([CallerMemberName]string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
The third and most recent method was (or will soon be) introduced in C#6.0 as part of .NET 4.5.3; the nameof
Operator:
public string TestValue
{
get { return testValue; }
set { testValue = value; NotifyPropertyChanged(nameof(TestValue)); }
}
protected virtual void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
My own assumption would be that the original, more error prone method of simply passing a string would be the most efficient, as I can only imagine that the other two methods use some form of reflection. However, I'm really keen to find out which of the other two methods is more efficient and whether there would actually be any difference between using the CallerMemberNameAttribute
attribute and the nameof
operator in a WPF context.
nameof
is a language feature and not a part of framework. – Foregut