Sunday 19 June 2016

Get the name of the Property of a class in C#

In this post we are going to see how to get the name of the Property of a class using C#, First we have to create a template class Employee, Then we have to create a static class to get the name of the property

    public class PropExtension
    {
        public static string GetPropName<TV>(Expression<Func<TV>> expression)
        {
            var _dat = (MemberExpression)expression.Body;
            return _dat.Member.Name;
        }
}


    public class Employee
    {
        public string Name { setget; }

        public string Role { setget; }
    
}

        
static void Main(string[] args)
{

       var propname = PropExtension.GetPropName((Employee e) => e.Role);
       Console.WriteLine(propname);
       Console.Read();

}


output:


From this post you can learn how to get the name of the Property of a class in C#