Click here to Skip to main content
15,881,413 members
Articles / Programming Languages / C#
Tip/Trick

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 16.8K   4   7
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:

C#
class County
{
  int CountryCode;
  string CountryName;
}


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

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


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.

License

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


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

Comments and Discussions

 
GeneralRe: In which case, congrats (and thanks)! Keep it up. Especially... Pin
Jonathon Bolster16-Dec-11 9:40
Jonathon Bolster16-Dec-11 9:40 
GeneralHow can you get the property name? Both CountryCode and Coun... Pin
Tiefeng You19-Dec-11 10:54
Tiefeng 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
Fréderic Cordier24-Dec-11 3:15 
Take a look at this blog post on static reflection:
http://blogs.u2u.be/kris/post/2009/06/29/Static-Reflection-in-NET.aspx
GeneralSometimes you have to use a string. For example, I use NHibe... Pin
Jonathon Bolster16-Dec-11 4:14
Jonathon Bolster16-Dec-11 4:14 
GeneralRe: Thanks Jonathon for explaining the utility. This is the firs... Pin
ARanadhir16-Dec-11 6:48
ARanadhir16-Dec-11 6:48 
GeneralExcuse me, i don't understand the utility ?? Pin
Yeurl_200716-Dec-11 3:53
Yeurl_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.