Consider the following code:
string propertyName;
var dateList = new List() { DateTime.Now };
propertyName = dateList.GetPropertyName(dateTimeObj
This is the version I use, it returns a PropertyInfo
, but getting the name is trivial.
public static PropertyInfo GetProperty(Expression> expression)
{
MemberExpression memberExpression = null;
if (expression.Body.NodeType == ExpressionType.Convert)
{
memberExpression = ((UnaryExpression) expression.Body).Operand as MemberExpression;
}
else if (expression.Body.NodeType == ExpressionType.MemberAccess)
{
memberExpression = expression.Body as MemberExpression;
}
if (memberExpression == null)
{
throw new ArgumentException("Not a member access", "expression");
}
return memberExpression.Member as PropertyInfo;
}