just.another.programmer
just.another.programmer

Reputation: 8785

Why does my AssignmentExpression automatically become a return statement when I put it in a LambdaExpression

I'm making an assignment inside a LambdaExpression. For some reason, the lambda is treating that assignment as the return type of the lambda as well.

var localIntVar = Expression.Variable(typeof(int));
var assign = Expression.Assign(localIntVar, Expression.Constant(5));
var block = Expression.Block(new ParameterExpression[]{localIntVar}, assign);
var lambda = Expression.Lambda(block);

lambda.Dump();

The generated lambda is of type Func<Int32>. I expected it to be Action. If I add an Expression.Empty() to the end of the block, it works as expected.

var localIntVar = Expression.Variable(typeof(int));
var assign = Expression.Assign(localIntVar, Expression.Constant(5));
var block = Expression.Block(new ParameterExpression[]{localIntVar}, assign, Expression.Empty());
var lambda = Expression.Lambda(block);

lambda.Dump();

Upvotes: 1

Views: 73

Answers (2)

AdamStone
AdamStone

Reputation: 158

In the first example you are invoking this overload of Block() which accepts a collection of ParameterExpression. In the second example you are invoking a different overload of Block() that specifies a block expression with no variables.

Try this:

var localIntVar = Expression.Variable(typeof(int));
var assign = Expression.Assign(localIntVar, Expression.Constant(5));
var block = Expression.Block(localIntVar, assign, Expression.Empty());
var lambda = Expression.Lambda(block);

Upvotes: 0

nemesv
nemesv

Reputation: 139758

From the documentation of the Expression.Block method:

When the block expression is executed, it returns the value of the last expression in the block.

So it is not the assignment expression is treated as return value but any expression which stands as the last parameter of the Expression.Block method.

Upvotes: 2

Related Questions