I resolved this! The problem was the IfThenElse
expression neither does an implicit return like a Block
does, nor does it allow an explicit return using an Expression.Return
(at least not as far as I could tell, unless I was doing them wrong), the solution was to change the code so the IfThenElse
assigned a return value, and at the end of the block I just put the return value for the implicit return.
Here's the fixed code:
public static Expression<Func<T, V>> AddClause<T, U, V>(this Expression<Func<T, U>> firstExpressionToExecute, Expression<Func<U, V>> secondExpressionToExecute)
{
var initialParameter = Expression.Parameter(typeof(T), "initialParameter");
var firstExpressionResult = Expression.Variable(typeof(U), "firstExpressionsResult");
var nullValueExpression = Expression.Variable(typeof(U), "nullValueExpression");
var returnValue = Expression.Variable(typeof(V), "returnValue");
var defaultExpressionResult = Expression.Variable(typeof(V), "defaultExpressionResult");
return Expression.Lambda<Func<T, V>>(
Expression.Block(
typeof(V),
new ParameterExpression[] { firstExpressionResult, defaultExpressionResult, nullValueExpression, returnValue },
new Expression[] {
Expression.Assign(firstExpressionResult, Expression.Invoke(firstExpressionToExecute, initialParameter)),
Expression.IfThenElse(
Expression.Equal(firstExpressionResult, nullValueExpression),
Expression.Assign(returnValue, defaultExpressionResult),
Expression.Assign(returnValue, Expression.Invoke(secondExpressionToExecute, firstExpressionResult))),
returnValue
}),
initialParameter);
}