I\'m trying to create a method using an expression tree that returns an object, but I can\'t figure out how to actually specify the object to return. I\'ve tried reading this, b
Apparently a return
is a GotoExpression that you can create with the Expression.Return factory method. You need to create a label at the end to jump to it. Something like this:
// an expression representing the obj variable
ParameterExpression objExpression = ...;
LabelTarget returnTarget = Expression.Label(typeof(StructType));
GotoExpression returnExpression = Expression.Return(returnTarget,
objExpression, typeof(StructType));
LabelExpression returnLabel = Expression.Label(returnTarget, defaultValue);
BlockExpression block = Expression.Block(
/* ... variables, all the other lines and... */,
returnExpression,
returnLabel);
The types of the label target and the goto expression must match. Because the label target has a type, the label expression must have a default value.