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:
So what is your suggestion to get property type?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With