2

Here's a follow-up question to Get name of property as a string.

Given a method Foo (error checking omitted for brevity):

// Example usage: Foo(() => SomeClass.SomeProperty)
// Example usage: Foo(() => someObject.SomeProperty)
void Foo(Expression<Func<T>> propertyLambda)
{
    var me = propertyLambda.Body as MemberExpression;
    var pi = me.Member as PropertyInfo;
    bool propertyIsStatic = pi.GetGetMethod().IsStatic;
    object owner = propertyIsStatic ? me.Member.DeclaringType : ???;
    ...
    // Execute property access
    object value = pi.GetValue(owner, null);
}

I've got the static property case working but don't know how to get a reference to someObject in the instance property case.

Thanks in advance.

Community
  • 1
  • 1
Jim C
  • 4,517
  • 7
  • 29
  • 33
  • Is there a reason that you want to invoke this using reflection rather than compiling the lambda? That appears to be the only reason that you need the owner in the first place... – Adam Robinson May 12 '10 at 20:53
  • The only reason being I'm a lambda newbie :) How would I execute the property access using just the lambda? I just tried this (as a guess): var v = Expression.Lambda>(propertyLambda).Compile(); object o = v(); but didn't get an intelligible result. – Jim C May 12 '10 at 21:20
  • Cool...this works: object o = Expression.Lambda(propertyLambda.Body).Compile().DynamicInvoke(); Thanks for the hint, Adam. – Jim C May 12 '10 at 21:35

1 Answers1

1

MemberExpression has a property called Expression, which is the object on which the member access occurs.

You can get the object by compiling a function which returns it:

var getSomeObject = Expression.Lambda<Func<object>>(me.Expression).Compile();

var someObject = getSomeObject();
Bryan Watts
  • 44,911
  • 16
  • 83
  • 88
  • That is amazingly cool, and exactly what I needed, in under 4 minutes, even. Sometimes I feel like I'm in a Star Trek episode and all I need to do when I'm stuck is call out, "Computer, what is..." :) Thanks Bryan. – Jim C May 12 '10 at 20:56
  • Haha happy to be of help. I happened to have a solution open in which I have code that extracts property getters from expressions :-) – Bryan Watts May 12 '10 at 21:11