Click here to Skip to main content
12,898,516 members (65,415 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

14.6K views
5 bookmarked
Posted 7 Feb 2010

Getting Property Name using LINQ

, 7 Feb 2010 CPOL
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
}

: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...

Pro

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    Praise Praise    Rant Rant    Admin Admin   

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170424.1 | Last Updated 8 Feb 2010
Article Copyright 2010 by Arun Jacob
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid