It can't be done with nameof
, but there's an even better way (available since C# 5). You can make the propertyName
parameter optional and apply the CallerMemberName
attribute to it:
protected void Set<T>(T value, [CallerMemberName] string propertyName = null)
{
...
}
protected T Get<T>([CallerMemberName] string propertyName = null)
{
...
}
Now if you omit the argument for propertyName
, the current member name is passed implicitly:
public string MyProperty
{
get { return base.Get<string>(); } // same as calling Get<string>("MyProperty")
set { base.Set<string>(value); } // same as calling Set<string>(value, "MyProperty")
}
nameof(MyProperty)
should work just fine? – Cassellnameof(MyProperty)
? – CertesMyProperty
might change: then, you have to remember to updatenameof(whatever)
, although the Visual Studio IDE should catch this problem. – Diannadiannenameof
. – CertesRaisePropertyChanged(nameof(ThisProperty))
method and trying to avoid cut and paste issues when generating new properties. I then looked more closely at MVVMLight's method signature and saw they already have an overload forRaisePropertyChanged()
defined aspublic virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null);
exactly for this purpose :-) – Deuterium