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
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);
You can use this:
var p = Expression.Parameter(a.GetType(), "x");
var body = Expression.Property(p, "SomePropertyName");
Expression.Lambda(body, p);