How to extract object reference from property access lamda
- by Jim C
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.