user7784348
user7784348

Reputation: 265

C# Expression Tree Accessing Result from another Expression

I have below method which gives a Expression<Func<T, Result<T>>> type.

public Expression<Func<T, Result<T>>> GetExpression<T>()
{
    //Do something to retrun expression
}



public class Result<T>
    {
        public bool IsSuccess { get; set; }

        public string Message { get; set; }

        public Result<T> ChildResult { get; set; }
    }

Now I have another method as shown below where I want to access to return result from GetExpression method.

public void UseExpression<T>()
        {
            var expression = GetExpression<T>();

            //I want to get the expression for return Result<T> from above method call and get access to it's properties like IsSuccess which can itself be a binary expression

        }

I want to get the expression for return Result from above method call and get access to it's properties like IsSuccess which can itself be a binary expression. All this without compiling the expression.

End goal: Let's think of it as a method call, method M1 returns Result R1 and method M2 uses this result R1 which(M2) has to create its own result R2 but method M2 has to do an Epxression.Or() on the IsSuccess property of R1 with some other bool expression to create R2 so we need the express. So we need to just get the IsSuccess property from R1 in M2 and then use it.

Please suggest how can I achieve it?

Thanks in advance.

Upvotes: 1

Views: 372

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062550

but in UseExpression method I'm creating new expression which won't be using compiled expression, so it all has to be expressions

There are two ways to do this.

The first way is to take the expression.Body which gives you the inner expression tree, and either re-use the expression.Parameters to build your new expression (assuming it still takes the same parameter types), or use an ExpressionVisitor to replace the parameters throughout the current .Body with whatever it should now be. If you have a concrete example of what you're trying to do, I could illustrate this with a complete example.

The second way is to use .Invoke in your new expression, passing the entire expression as the first parameter, and supplying whatever your new expression wants to use as the parameters as the parameters. However, this is slightly less reliable if it is going to be passed to something like EF, and it may decide that it isn't supported. If you're going to call .Compile you should be fine, though.

Upvotes: 1

Related Questions