Saturday, 28 February 2015

how to read class property name in c#

Dynamically retrieve and save property name and value into the database That can be possible if you are able to read the class property dynamically, and later on retrieve it from the database and invoke the property values

If you have already get work done that how to save the property name in the database, then use Get Property is the way to go on the retrieval of property.

Use Gettype to get the class types. 



Below code Snippet will give the way that How to read class property name in C# code;


Code Snippet
/// <summary>
        /// Returun the list of propert name of the Class
        /// </summary>
        /// <param name="objValue"></param>
        /// <returns></returns>
        public List<string> GetPropertiesListOfClass<T>(T objValue)
        {
            List<string> oPropertyList = new List<string>();
             Type t = objValue.GetType();
             foreach (PropertyInfo pi in t.GetProperties())
             {
                 oPropertyList.Add(pi.Name);
             }
             return oPropertyList;

        }

Follow below code by passing the property type in the c# code will give you the property name.
Dynamically by passing the Property Type the below piece of code give the property name;


  /// <summary>
        /// Get the name of Property At run time  of any given class
        /// Call it like GetPropertyName<Foo>(x => x.Bar)
        /// </summary>
        /// <typeparam name="TClass"></typeparam>
        /// <param name="propertyExpression"></param>
        /// <returns></returns>
        public static string GetPropertyName<TClass>(
    Expression<Func<TClass, object>> propertyExpression)
        {
            var bodys = propertyExpression.Body as UnaryExpression;
           

            var memberExpressions = bodys.Operand as MemberExpression;
            var propertyInfos = memberExpressions.Member as PropertyInfo;
           

            return propertyInfos.Name;
        }

No comments:

Post a Comment

Others

You will like to read it