How can I determine the type of a property in 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 a string of type.

Where can I find the type?

1
4
6/26/2011 2:57:40 PM

Accepted Answer

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

You want the return type, I take it. Use if you wish to get the type that the method is defined on.memberExpression.Member.DeclaringType .

3
6/12/2015 12:26:57 AM

Popular Answer

This straightforward Expression Extension Method could be helpful to other people.

 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;
    }

Example of use:

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


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow