Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to deconstruct expression tree to get value of captured variable

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading