Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

Go to top

How to get property name using Expression

, 16 Dec 2011
Rate this:
Please Sign up or sign in to vote.
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. Smile | :)
 
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.

License

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

Share

About the Author

Jonathon Bolster
Web Developer
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
General. PinmemberARanadhir16-Dec-11 7:07 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140905.1 | Last Updated 16 Dec 2011
Article Copyright 2011 by Jonathon Bolster
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid