Thursday, September 4, 2014

How to get name of the member (property name, etc) of a .NET class without using hard-coded/ magic strings

Consider following sample class:

public class City()
{
public int CityId { get; set; }
public string CityName { get; set; }
}

For various reasons, we need name of the properties/ field of the class in a string variable in our code. (For example, while binding ID and Text fields in DropDown controls, etc).

One option which is quite easy is to use the hard-coded strings directly.
For exmaple,
string idField = "CityId";

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<City, int>>)(c => c.CityId)).Body).Member.Name;

string textField =
                ((MemberExpression)((Expression<Func<City, string>>)(c => c.CityName)).Body).Member.Name;

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

Hope this helps