How to Get Name of the Member (Property Name, etc.) of a .NET Class - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

Saturday, August 22, 2015

How to Get Name of the Member (Property Name, etc.) of a .NET Class

Consider the following sample class:

public class Person()
{
public int PersonId { get; set; }
public string PersonName { get; set; }
}

For various reasons, we need the name of the properties/ field of the class in a string variable in our code.

One option which is quite easy is to use the hard-coded strings directly.

For example:

string idField = "PersonId";

But the biggest disadvantage with the above approach is that whenever a field name or property name is changed, you will need to manually search and edit such string values. If you forget, it will not give you any compile error and you will only come to know when some exception will be thrown from your code.

In order to get rid of such issues, we should avoid using hard-coded values.

.NET 3.5 or higher provides support of encapsulating methods using Func helper which we can use to find a name of the property/field.

using System;
using System.Linq.Expressions;
string idField = ((MemberExpression)((Expression<Func<Person, int>>)(c => c.PersonId)).Body).Member.Name;
string textField = ((MemberExpression)((Expression<Func<Person, string>>)
(c => c.PersonName)).Body).Member.Name;

That means, now whenever some changes property "PersonId" to "Person_Id" or whatever, s/he must need to change the above code, otherwise it will always give a compile error.

I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too. 

Stay tuned to my blogtwitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.


This article is related to

C#,.NET,Architect,Intermediate,VS2010,.Net,Articles,Computer Tutorials

No comments:

Post a Comment