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?
You have to do quite a bit of casting to get to the underlying value of
ConstantExpressionsince the compiler will tuck the value away.The following gets the right node via
BinaryExpression, checks if the right node is aConstantExpression, and uses theFieldInfoof the right node to get the value: