How to deconstruct expression tree to get value of captured variable

Advertisements

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?

>Solution :

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"
}

Leave a ReplyCancel reply