Click here to Skip to main content

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...
Sign Up to vote bad good
Add a reason or comment to your vote: x
Votes of 3 or less require a comment
See more: C#.NETLINQ
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
}
Thumbs Up | :thumbsup:
Posted 7 Feb '10
Arun Jacob11.2K
Edited 7 Feb '10


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

Your Filters
Interested
Ignored
     
  1. Wonde Tadesse (1,210)
  2. SAKryukov (398)
  1. SAKryukov (9,712)
  2. Christian Graus (6,009)
  3. OriginalGriff (4,736)
  4. thatraja (4,349)
  5. Abhinav S (4,335)

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralNot LinQ PinmemberFZelle23:11 7 Feb '10  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.


Advertise | Privacy | Mobile
Web03 | 2.5.120210.1 | Last Updated 19 Mar 2011
Copyright © CodeProject, 1999-2012
All Rights Reserved. Terms of Use
Layout: fixed | fluid