Skip to content

Expression.TryFault returns incorrect result with return labels #114081

Closed as not planned
@MattEdwardsWaggleBee

Description

@MattEdwardsWaggleBee

Description

When using Expression.TryFault with a return label, compiling with preferInterpretation: true returns a different value than with preferInterpretation: false

Reproduction Steps

using static System.Linq.Expressions.Expression;

[TestClass]
public class ExpressionTests
{
    [DataTestMethod]
    [DataRow( false )]
    [DataRow( true )]
    public void TryFault_ShouldRunSuccessfully_WithReturnLabel( bool interpret )
    {
        var x = Parameter( typeof( int ), "x" );
        var resultLabel = Label( typeof( int ), "exit" );

        // Arrange
        var block = Block(
            [x],
            TryFault(
                Block(
                    Assign( x, Constant( 1 ) ),
                    Return( resultLabel, x )
                ),
                Assign( x, Constant( 2 ) )
            ),
            Label( resultLabel, defaultValue: Constant( 3 ) )
        );

        var lambda = Lambda<Func<int>>( block );
        var compiledLambda = lambda.Compile( preferInterpretation: interpret );

        // Act
        var result = compiledLambda();

        //Assert
        Assert.AreEqual( 1, result );
    }
}

Expected behavior

Both versions of the test should return 1

Actual behavior

When run with preferInterpretation, the result is 3, which is the default value of the return.

Regression?

No response

Known Workarounds

The current workaround is to write this as a TryFinally but with an additional parameter to track exceptions.

Configuration

  • Tested on .NET 8 and 9
  • Windows 11 Pro
  • Intel x64

I don't believe the configuration matters.

Other information

I assume there is something incorrect with the instructions for entering and exiting faults when using a return label.

private void CompileTryFaultExpression(TryExpression expr)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions