// Inside some Class ...
private string _MyProperty;
public string MyProperty {
get {
return _MyProperty;
}
set {
_MyProperty = value;
Notify():
}
}
void Notify([CallerMemberName] string propertyName = "") {
// notify observers
}
Basically, it captures the name of the caller and in the case of the property setter it would return the property name itself “MyProperty.”
I want to use this to notify observers thru targeted events. That is, only notifying observers when a property they registered for changes, in a similar way to KVO in Objective-C / Cocoa.
Now I believe the earliest Mono to support .NET > 4 (a 5 preview actually), is 2.11, while Unity as of now (4.3.x) is stuck with Mono 2.10.
Am I right? Please tell me I’m not and that CallerMemberInfoAttribute is hidden somewhere.
If I am right tough, does anyone have any thoughts on how to get a caller’s property name without stack tracking?
Still kind of hacky since it relies on knowledge that property accessors are named "get_PropertyName" and "set_PropertyName", but at least I don’t need to use System.Diagnostics or explicitly type the name of the property.
Still it’d be even better if CallerMemberName was supported in the Mono version in Unity, as it is faster than using reflection and would make it unnecessary to strip the string of the first 4 chars.
Try this. It’s one step better than just passing the name as a string as if you change the name of the property (but not the passed property) you’ll get a compiler error.
public string SomeProperty
{
get
{
NotifyOfPropertyChange(() => SomeProperty);
return "Test";
}
}
public void NotifyOfPropertyChange<TProperty>(Expression<Func<TProperty>> property)
{
var memberExpression = property.Body as MemberExpression;
var name = memberExpression.Member.Name;
// 'name' is a string holding the name of the property
}