Consider the following sample class:
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 string
s directly.
For example:
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 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.