I want to convert this:
Func<dynamic, object> myFunc = t => return t.Name + " " + t.Surname;
Into an Expression Tree.
What I have came up with, is this:
ParameterExpression target = ExpressionParameter(typeof(dynamic), "target");
ParameterExpression result = ExpressionParameter(typeof(object), "result");
BlockExpression block = Expression.Block(
new [] { result },
Expression.Assign(
result,
Expression.Add(
Expression.Add(
Expression.Property(target, "Name"),
Expression.Constant(" ", typeof(string))
),
Expression.Property(target, "Surname")
)
)
);
Func<dynamic, object> myFunc = Expression.Lambda<dynamic, object>>(block, target).Compile();
However, the compiler doesn't like typeof(dynamic)
, and I kind of get it. dynamic
isn't a type, it is an object
in essence.
So I proceeded to change the ParameterExpression
:
ParameterExpression target = ExpressionParameter(typeof(object), "target");
The code now compiles, but there is a problem at runtime.
I am trying to get the value of the property Name
of target
, which may have sense if the object was dynamic
.
But since target
is considered of type object
, the Expression throws an error telling me Name
doesn't exist as a property.
Is there an Expression for fetching a dynamic property?