Click here to Skip to main content
15,879,095 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

How to get property name using Expression

Rate me:
Please Sign up or sign in to vote.
4.90/5 (7 votes)
16 Dec 2011CPOL 32K   5   3
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)


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
dibley19736-Nov-15 3:47
dibley19736-Nov-15 3:47 
Questionuse same like this bt its working only string type properties Pin
abhijeet404619-Mar-14 1:20
abhijeet404619-Mar-14 1:20 
General. Pin
ARanadhir16-Dec-11 7:07
ARanadhir16-Dec-11 7:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.