Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

How to get property name using Expression

4.90/5 (7 votes)
16 Dec 2011CPOL 32.6K  
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:

C#
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:

C#
PropertyName<Country>(x=> x.CountryName)


The benefit here is that you don't have to instantiate a new object to get the property name.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)