I have got this class:
class foo
{
int val;
public int Val
{
set{ val = values; },
set{ val = values; }
}
}
I need to pass the property name to a DataBinding:
String propertyName = "Val";
ctrl.DataBindings.Add(propertyName, object, dataMember, true, DataSourceUpdateMode.Never);
I want to do something like this:
propertyName = typeof(foo).methods.Val.toString();
As of C# 6, you can use the nameof
operator:
ctrl.DataBindings.Add(nameof(foo.Val), /* other arguments as before */);
Before C# 6, there's no really simple way to do this at compile-time. One option, however, is to have unit tests which check that all your property names are actual properties (checking with reflection).
Also note that in C# 5 there's CallerMemberNameAttribute
which is useful for implementing INotifyPropertyChanged
- but isn't as useful for your case.
The approach of using expression trees works, but it feels somewhat clunky to me. Although far lower tech, simple string constants and a unit test feels a bit simpler.
See more on this question at Stackoverflow