views:

44

answers:

1

Is there a simple way to get the PropertyInfo for a property in a delegate, assuming it is a simple property seletor?

Example:

var propertyInfo = Method<MyClass,int>(s => s.Property);

...

PropertyInfo Method(Func<T1,T2> selector)
{
   // What goes here?
}
+6  A: 

Using Expression you can:

    static PropertyInfo ExtractProperty<T>(Expression<Func<T>> selector)
    {
        return (selector.Body as MemberExpression).Member as PropertyInfo;
    }
alexdej
yup, has to be an expression tree and not a delegate
Ben Voigt
I hadn't even considered this, thanks!
Paul