0

My problem is quite similar to this post (getting the object out of a memberexpression), however, it is different in that I need to get it from a field.

// how to get 1 from i?
int i = 1;
Expression<Func<int, int, bool>> a = (x1, x2) => x1 == i;
BinaryExpression x = (BinaryExpression)a.Body;
x.Right.//What now?

I cannot use get type.getmember.getvalue as in the linked example because i is a local variable. So how would I extract the value of a field or local variable (not necessarily local to where I am trying to extract)?

Community
  • 1
  • 1
TheCatWhisperer
  • 901
  • 2
  • 12
  • 28
  • possible duplicate of [force Expression<> to evaluate local variables](http://stackoverflow.com/questions/12734464/force-expression-to-evaluate-local-variables) – Grundy Mar 27 '15 at 20:52

2 Answers2

2

Actually you can do the same as did in referenced link even if i is a "local variable" because in your case i isn't local variable anymore. Let's print our lambda:

Console.WriteLine((Expression<Func<int, int, bool>>) ((x1, x2) => x1 == i));

the output will be something about:

(x1, x2) => (x1 == value(ConsoleApplication4.Program+<>c__DisplayClass0).i)

Quite the same you can see if you decompile the code with closures.

So the code from the link will work just fine:

int i = 1;
Expression<Func<int, int, bool>> a = (x1, x2) => x1 == i;
BinaryExpression x = (BinaryExpression)a.Body;

var me = (MemberExpression) x.Right;
var ce = (ConstantExpression) me.Expression;
var fieldInfo = (FieldInfo)me.Member;
Console.WriteLine(fieldInfo.GetValue(ce.Value));
ie.
  • 5,982
  • 1
  • 29
  • 44
1

It's possible to compile and execute the expression:

var data = Expression.Lambda (x.Right).Compile ().DynamicInvoke ();
cansik
  • 1,924
  • 4
  • 19
  • 39