How to get the type of a property used within a generic expression?

c# expression expression-trees generics

Question

public static void Map<T>(Expression<Func<T, object >> expression)
{
    var memberExpression = (expression.Body as UnaryExpression).Operand as MemberExpression;
    var name = memberExpression.Member.Name;
}

Usage:

Map<Article>(x => x.Name)

Name is of type string.

How do I get the type?

Accepted Answer

var returnType = memberExpression.Member is MethodInfo 
    ? ((MethodInfo)memberExpression.Member).ReturnType 
    : ((PropertyInfo)memberExpression.Member).PropertyType;

I assume you want the return type. If you want the type on which the method is defined, use memberExpression.Member.DeclaringType.


Popular Answer

Here is a simple Expression Extension Method that may be useful to others.

 public static Type GetPropertyType<TModel, TValue>(this Expression<Func<TModel, TValue>> expression)
    {
        var body = expression.Body as MemberExpression;
        if (body == null)
        {
            throw new ArgumentException("'expression' should be a member expression");
        }
        return ((PropertyInfo)body.Member).PropertyType;
    }

Sample usage:

if (expression.GetPropertyType() == typeof(DateTime))


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why