Thursday, February 4, 2010

Getting Property Name using LINQ

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
}

1 comments:

ജയരാജ്‌മുരുക്കുംപുഴ said...

arivu nalkanulla sanmanassinu nandi........

Post a Comment