Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

How to Get Name of the Member (Property Name, etc.) of a .NET Class Without Using Hard-coded/ Magic Strings

3.65/5 (12 votes)
20 May 2018CPOL1 min read 19.2K  
How to get name of the member (property name, etc.) of a .NET class without using hard-coded/ magic strings

Consider the following sample class:

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

For various reasons, we need the 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 example:

C#
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.

C#
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 need to change the above code, otherwise it will always give a compile error.

Hope this helps!

Updates

  • 21/May/2018: As pointed out by many in the comments section - if you are using C# 6.0 or higher, then the above approach is not recommended. Instead, use nameof operator.

License

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