Here is a static class used to get the name of one of the properties on your class.
public static class MemberName<T>
{
public static string Of(Expression<Func<T, object>> expression)
{
MemberExpression memberExpression;
if (expression.Body.NodeType == ExpressionType.Convert)
memberExpression = expression.Body.To<UnaryExpression>().Operand.To<MemberExpression>();
else
memberExpression = expression.Body.To<MemberExpression>();
return memberExpression.Member.Name;
}
}
You can call the class as follows:
string heightPropertyName = MemberName<Person>.Of(x => x.Height);
This allows us to stop using ‘magic’ strings that are not tightly coupled with the actual property. If you change the name of your property, using this class you can always get the new string value of that property. This is most useful when you’re databinding, or passing the name of the property to nhibernate.
This code uses an extension method call To
public static T To<T>(this object obj)
{
return (T)obj;
}
Without the extension method line 8 becomes the following:
memberExpression = (MemberExpression)((UnaryExpression)expression.Body).Operand;

Categories
Tag Cloud
Blog RSS
Comments RSS
Last 50 Posts
Back
Void « Default
Life
Earth
Wind
Water
Fire
Light 