Jim C
Jim C

Reputation: 4648

How to extract object reference from property access lambda

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.

Upvotes: 2

Views: 743

Answers (1)

Bryan Watts
Bryan Watts

Reputation: 45445

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

Upvotes: 1

Related Questions