Click here to Skip to main content
15,885,435 members
Articles / Programming Languages / C#
Tip/Trick

Getting Property Name using LINQ

Rate me:
Please Sign up or sign in to vote.
3.75/5 (6 votes)
7 Feb 2010CPOL 22.5K   5   2
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)


Written By
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


Comments and Discussions

 
GeneralMy vote of 1 Pin
Shimmy Weitzhandler9-Jun-12 14:06
Shimmy Weitzhandler9-Jun-12 14:06 
GeneralNot LinQ Pin
FZelle7-Feb-10 22:11
FZelle7-Feb-10 22:11 
This is not LinQ, this are Expressiontrees, that are Part of C# 3.
LinQ is based on this technic but not the other way round.

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.