Search code examples
c#linq-expressions

Getting a local variable out of a lambaexpression


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)?


Solution

  • 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));