views:

48

answers:

1

Here's a follow-up question to http://stackoverflow.com/questions/2820660/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.

+1  A: 

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