I'm experimenting with C# Expression Trees and trying to understand the difference between Expression.Return and Expression.Goto. I can’t create an example where Return and Goto behave differently inside a block. I want to clearly understand when to use one over the other in expression tree generation.
Example
[Fact]
public void Block_Return_LikeGoto()
{
var type = typeof(int);
var label1 = Expression.Label(type);
var label2 = Expression.Label(type);
var body = Expression.Block(
Expression.Return(label1, Expression.Constant(1)),
Expression.Label(label1, Expression.Constant(2)),
Expression.Label(label2, Expression.Constant(3)));
var func = Expression.Lambda<Func<int>>(body).Compile();
Assert.Equal(3, func());
}
Here, Return does not exit the block immediately; the label’s value is returned at the end of the block, so the behavior is the same as using Goto.
When exactly do
ReturnandGotobehave differently?Are there cases where
Gotocan never replaceReturn?