Thursday, April 10, 2014

Dynamic Reflection in C#

Hi,

More and more I started to feel the need for dynamic reflection - reflection working not based on subject names (properties, methods, fields ,...) but delegates.
So got time to submit and idea on Microsoft Connect about it. The following sample shows what the idea is about:
internal class Sample
{
 public int PropA { get; set; }
 public void SomeMethod()
 {
  PropertyInfo info = GetPropertyInfo(() => this.PropA);
  // Some other code, using the "info" variable
 }

 public static PropertyInfo GetPropertyInfo(Func<object> property)
 {
  // This is the method I'm asking about.
 }
}
If you like it, please go and vote for it at: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/5755035-ability-to-get-propertyinfo-dynamically-passing-th


Update:
It turns out what I've asked in this post is possible using Expression trees. The following is the working example on how to achieve it:
    public static class PropertyExtensions
    {
        public static PropertyInfo GetPropertyInfo<TSource, TProperty>(this TSource instance, Expression<Func<TSource, TProperty>> propExtractor)
        {
            MemberExpression mexp = propExtractor.Body as MemberExpression;
            if (mexp == null)
            {
                throw new ArgumentException("Invalid");
            }
            PropertyInfo result = mexp.Member as PropertyInfo;
            if (result == null)
            {
                throw new ArgumentException("Invalid expression");
            }
            return result;
        }
    }