Using reflection to access property names from the class in ASP.NET MVC

There are sometimes situations where we want to to find out what is the name of the property of the class when application is running.

To access name of the single property we use reflection:

public static string GetPropertyName<T, TValue>(Expression<Func<T, TValue>> memberAccess)
{
    return ((MemberExpression)memberAccess.Body).Member.Name;
}
We can access all properties without writing static method.

foreach (var item in new T().GetType().GetProperties())
{
    // Get name for single item -  item.Name.ToString()
} 


Comments