Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get property type by MemberExpression

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?

like image 532
Saeid Avatar asked Apr 19 '12 08:04

Saeid


1 Answers

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;
    }
}
like image 85
Trevor Pilley Avatar answered Sep 24 '22 14:09

Trevor Pilley