Click here to Skip to main content
11,641,209 members (62,424 online)
Click here to Skip to main content

Tagged as

Getting Property Name using LINQ

, 7 Feb 2010 CPOL 12K 5
Rate this:
Please Sign up or sign in to vote.
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
}
Thumbs Up | :thumbsup:

License

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

Share

About the Author

Arun Jacob
Software Developer Tata Consultancy Services
India India
I have been working in different .NET Technologies like ASP.NET,WPF,Silverlight for the last few years.I am enjoying my life as a Programmer and spending time with my Family,Friends & Camera.

My Technical Blog


My Photo Blog


You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 1 Pin
Shimmy Weitzhandler9-Jun-12 14:06
memberShimmy Weitzhandler9-Jun-12 14:06 
GeneralNot LinQ Pin
FZelle7-Feb-10 22:11
memberFZelle7-Feb-10 22:11 

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 | Terms of Use | Mobile
Web01 | 2.8.150731.1 | Last Updated 8 Feb 2010
Article Copyright 2010 by Arun Jacob
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid