Click here to Skip to main content
15,073,462 members
Articles / Programming Languages / C#
Posted 16 Dec 2011

Tagged as


4 bookmarked

How to get property name using Expression

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
16 Dec 2011CPOL
How to get property name using Expression
Expression Trees
Expression trees represent code in a tree-like data structure where each node is an expression, for example, a method call or a binary operation such as x < y.

Using the above feature, we can retrieve the property name of class:

class County
  int CountryCode;
  string CountryName;

To retreive the name of property: "CountryName" of class, we build the following expression:

Country c = new Country();
Expression<Func<string>> exp =() => c.ContryName;
string propName = exp.Body.ToString().Substring(exp.Body.ToString().LastIndexOf('.') + 1);

Use of the GetProperty in this case is redundant, because we need to know the property name to call the method.

Please let me know if it is useful.


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


About the Author

United States United States
No Biography provided

Comments and Discussions

GeneralRe: In which case, congrats (and thanks)! Keep it up. Especially... Pin
Jonathon Bolster16-Dec-11 9:40
MemberJonathon Bolster16-Dec-11 9:40 
GeneralHow can you get the property name? Both CountryCode and Coun... Pin
Tiefeng You19-Dec-11 10:54
MemberTiefeng You19-Dec-11 10:54 
GeneralRe: Take a look at this blog post on static reflection: http://b... Pin
Fréderic Cordier24-Dec-11 3:15
MemberFréderic Cordier24-Dec-11 3:15 
Take a look at this blog post on static reflection:
GeneralSometimes you have to use a string. For example, I use NHibe... Pin
Jonathon Bolster16-Dec-11 4:14
MemberJonathon Bolster16-Dec-11 4:14 
GeneralRe: Thanks Jonathon for explaining the utility. This is the firs... Pin
ARanadhir16-Dec-11 6:48
MemberARanadhir16-Dec-11 6:48 
GeneralExcuse me, i don't understand the utility ?? Pin
Yeurl_200716-Dec-11 3:53
MemberYeurl_200716-Dec-11 3:53 
QuestionI'm curious as to how this is usefull? Pin
Daniel Gidman21-Dec-11 8:01
professionalDaniel Gidman21-Dec-11 8:01 

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.