Get property type by MemberExpression
Asked Answered
O

1

21

I ask similar question here , assume this type:

 public class Product {

public string Name { get; set; }
public string Title { get; set; }
public string Category { get; set; }
public bool IsAllowed { get; set; }

}

and this one that use MemberExpression :

public class HelperClass<T> {

    public static void Property<TProp>(Expression<Func<T, TProp>> expression) {

        var body = expression.Body as MemberExpression;

        if(body == null) throw new ArgumentException("'expression' should be a member expression");

        string propName = body.Member.Name;
        Type proptype = null;

    }

}

I use it like this:

HelperClass<Product>.Property(p => p.IsAllowed);

in HelperClass I just need property name(in this example IsAllowed) and property type (in this example Boolean) So I can get property name but I can't get property type. I see the property type in debugging as following picture shown:

enter image description here

So what is your suggestion to get property type?

Onrush answered 19/4, 2012 at 8:15 Comment(0)
R
40

Try casting body.Member to a PropertyInfo

public class HelperClass<T>
{
    public static void Property<TProp>(Expression<Func<T, TProp>> expression)
    {
        var body = expression.Body as MemberExpression;

        if (body == null)
        {
            throw new ArgumentException("'expression' should be a member expression");
        }

        var propertyInfo = (PropertyInfo)body.Member;

        var propertyType = propertyInfo.PropertyType;
        var propertyName = propertyInfo.Name;
    }
}
Radiolarian answered 19/4, 2012 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.