2

Consider the following block of code:

Expression<Func<string, bool>> pred;
{
    string s = "test";
    pred = x => x == s;
}
// how to retrieve the value of s from just pred?

The only variable in scope after this block is pred. How can we retrieve the value of the captured variable s, just using pred? I can see the value in the debugger by expanding the object graph of pred, but how do I do that in code?

5
  • pred.Body.Right.Expression.Value.s Commented Sep 7, 2022 at 15:21
  • @MathiasR.Jessen Right won't be available. Commented Sep 7, 2022 at 15:23
  • @MathiasR.Jessen You need to do some intermediate casting to make that work Commented Sep 7, 2022 at 15:24
  • And even then you need to do some funkiness with the generated class to get s Commented Sep 7, 2022 at 15:27
  • This question will give you an insight on how to drill into the value properly Commented Sep 7, 2022 at 15:38

1 Answer 1

4

You have to do quite a bit of casting to get to the underlying value of ConstantExpression since the compiler will tuck the value away.

The following gets the right node via BinaryExpression, checks if the right node is a ConstantExpression, and uses the FieldInfo of the right node to get the value:

var rightNodeMemberExpression = ((pred.Body as BinaryExpression).Right) 
                                    as MemberExpression;
var fieldInfo = rightNodeMemberExpression.Member as FieldInfo;

if (rightNodeMemberExpression.Expression is ConstantExpression exp)
{
    var val = exp.Value;
    var retrievedValue = fieldInfo.GetValue(val);

    Console.WriteLine(retrievedValue); // will output "test"
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.