Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating expression tree for accessing a Generic type's property

I need to write a generic method which takes the instance of the generic type and the property name in string format and return an Expression tree

I need to convert a simple lambda expression

a => a.SomePropertyName

where a is generic type which will have a property by the name SomePropertyName

I know that we can get the property information using the following reflection code

System.Reflection.PropertyInfo propInfo = a.GetType().GetProperty("SomePropertyName");

This might be very simple, but I'm not well versed with Expression trees, If there is a similar question, please link it and close this

like image 804
Vamsi Avatar asked Jan 24 '13 11:01

Vamsi


2 Answers

You can use this:

var p = Expression.Parameter(a.GetType(), "x");
var body = Expression.Property(p, "SomePropertyName");

Expression.Lambda(body, p);
like image 63
Daniel Hilgarth Avatar answered Nov 10 '22 06:11

Daniel Hilgarth


Assuming the parameter type and return type aren't known in advance, you may have to use some object, but fundamentally this is just:

var p = Expression.Parameter(typeof(object));
var expr = Expression.Lambda<Func<object, object>>(
    Expression.Convert(
        Expression.PropertyOrField(
             Expression.Convert(p, a.GetType()), propName), typeof(object)), p);

If the input and output types are known, you can tweak the Func<,> parameters, and maybe remove the Expression.Convert. At the extreme end you can get a lambda without knowing the signature of lambda, via:

var p = Expression.Parameter(a.GetType());
var expr = Expression.Lambda(Expression.PropertyOrField(p, propName), p);
like image 27
Marc Gravell Avatar answered Nov 10 '22 07:11

Marc Gravell