score:2

Accepted answer

the lambda in your example has "closed over" the testvalue variable, meaning the compiler has captured it as a field of the same name in an automatically generated class called consoleapplication1.program+<>c__displayclass1>. you can use normal reflection to get the current value of that field by casting the right hand-side of the binary expression into a memberexpression.

var testvalue = "hello";
var expr = (expression<func<string, bool>>) (x => x == testvalue);
var rhs = (memberexpression) ((binaryexpression) expr.body).right;
var obj = ((constantexpression) rhs.expression).value;
var field = (fieldinfo) rhs.member;
var value = field.getvalue(obj);
debug.assert(equals(value, "hello"));
testvalue = "changed";
value = field.getvalue(obj);
debug.assert(equals(value, "changed"));

alternatively you can change your variable into a constant.

const string testvalue = "hello";
var expr = (expression<func<string, bool>>) (x => x == testvalue);
var value = ((constantexpression) ((binaryexpression) expr.body).right).value;
debug.assert(equals(value, "hello"));

score:0

instead of doing this by yourself, have a look at partialevaluator from matt warren. it replaces all references to constants with the constants themselves.


Related Query

More Query from same tag