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

Getting Property Name using LINQ

3.75/5 (6 votes)
7 Feb 2010CPOL 23K  
Sometimes we want to compare the property names like,if (e.PropertyName == FirstName){//Do Something}But this is not type safe. If we change the property name then this won’t work as expected and also it won’t throw compile time error. For getting property name for Type safe...
Sometimes we want to compare the property names like,
if (e.PropertyName == "FirstName")
{
//Do Something
}

But this is not type safe. If we change the property name then this won’t work as expected and also it won’t throw compile time error. For getting property name for Type safe operations we can use LINQ. So if you change property name in future, you’ll get compile time error.
public string GetPropertyName<T>(Expression<Func<T>> expression)
{
   MemberExpression memberExpression=(MemberExpression)expression.Body;
   return memberExpression.Member.Name;
}

We can call this method using Expression Lambdas like,
if (e.PropertyName == GetPropertyName(() => Customer.FirstName))
{
  //Do Something
}

:thumbsup:

License

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