Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

How to get property name using Expression

4.00/5 (1 vote)
16 Dec 2011CPOL 17.5K  
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)