Okay magic strings are a pain, in the worst cases they're bugs waiting to happen but I've been living with the following for while and it's always been nagging me when ever I look at the code.
So after reading the MSDN article by Jeremy Miller and the example of using the Lambda expression in Fluent nHibernate mapping syntax I thought can we apply this to the above to remove the magic string "Id", and the answer is yes!
public abstract class Observable<T> : IEntity<T>, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private T _id;
public virtual T Id
{
get { return _id; }
private set { ChangePropertyAndNotify(ref _id, value, "Id"); }
}
protected void ChangePropertyAndNotify<T2>(ref T2 value, T2 newValue, string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
So after reading the MSDN article by Jeremy Miller and the example of using the Lambda expression in Fluent nHibernate mapping syntax I thought can we apply this to the above to remove the magic string "Id", and the answer is yes!
public abstract class Observable<T> : IEntity<T>, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private T _id;
public virtual T Id
{
get { return _id; }
private set { ChangePropertyAndNotify(ref _id, value, x => Id); }
}
protected void ChangePropertyAndNotify<T2>(ref T2 value, T2 newValue, Expression<Func<object, T2>> expression)
{
value = newValue;
var propertyName = ((MemberExpression)expression.Body).Member.Name;
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
The power of this is the Expression syntax and the ability at runtime to query and manipulate for other purposes other than what it was directly designed for.
Now is there a performance penalty for doing this?
Simple answer is I don't care until it becomes a problem, and to be honest I don't currently think it's going to be - avoid premature optimization at all costs, they're distractions from the requirement.
Awkward Coder
Comments
Post a Comment