65.9K
CodeProject is changing. Read more.
Home

How to get property name using Expression

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Dec 16, 2011

CPOL
viewsIcon

17510

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);
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.