65.9K
CodeProject is changing. Read more.
Home

How to get property name using Expression

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.90/5 (7 votes)

Dec 16, 2011

CPOL
viewsIcon

32611

Nice, I do like the expression trees. :)Unfortunately, I can't remember the reference I used to make this one, but I find the property name in a slightly different way:public static string PropertyName(Expression> expression){ var body = expression.Body as...

Nice, I do like the expression trees. :) Unfortunately, I can't remember the reference I used to make this one, but I find the property name in a slightly different way:
public static string PropertyName<T>(Expression<Func<T, object>> expression)
{
    var body = expression.Body as MemberExpression;

    if (body == null)
    {
        body = ((UnaryExpression)expression.Body).Operand as MemberExpression;
    }

    return body.Member.Name;
}
Then, I can just use the following to get the property name:
PropertyName<Country>(x=> x.CountryName)
The benefit here is that you don't have to instantiate a new object to get the property name.