How to extract object reference from property access lamda

Posted by Jim C on Stack Overflow See other posts from Stack Overflow or by Jim C
Published on 2010-05-12T20:37:03Z Indexed on 2010/05/12 20:44 UTC
Read the original article Hit count: 165

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about reflection