title: Faster way to cast a Func<T, T2> to Func<T, object>?
body: <p>Is there a faster way to cast <code>Fun&lt;TEntity, TId&gt;</code> to <code>Func&lt;TEntity, object&gt;</code></p>
  
  <pre><code>public static class StaticAccessors&lt;TEntity&gt;
  {
   public static Func&lt;TEntity, TId&gt; TypedGetPropertyFn&lt;TId&gt;(PropertyInfo pi)
   {
    var mi = pi.GetGetMethod();
    return (Func&lt;TEntity, TId&gt;)Delegate.CreateDelegate(typeof(Func&lt;TEntity, TId&gt;), mi);
   }
  
   public static Func&lt;TEntity, object&gt; ValueUnTypedGetPropertyTypeFn(PropertyInfo pi)
   {
    var mi = typeof(StaticAccessors&lt;TEntity&gt;).GetMethod("TypedGetPropertyFn");
    var genericMi = mi.MakeGenericMethod(pi.PropertyType);
    var typedGetPropertyFn = (Delegate)genericMi.Invoke(null, new[] { pi });
  
    //slow: lambda includes a reflection call
    return x =&gt; typedGetPropertyFn.Method.Invoke(x, new object[] { }); //can we replace this?
   }
  }
  </code></pre>
  
  <p>Is there a way to convert <code>typedGetPropertyFn</code> to a <code>Func&lt;TEntity, object&gt;</code> without having reflection code in the returned lambda like the example above?</p>
  
  <blockquote>
    <p>EDIT: added modified solution</p>
  </blockquote>
  
  <p>Ok thanks to 280Z28 for leading me down the right path which I've included in the final solution below. I've left the reflection code in there for platforms that don't support Expressions. For platforms that do it's showing a <strong>26x</strong> to <strong>27x</strong> (13 / .5 ticks avg) perf increase for getting <code>int</code> and <code>string</code> properties.</p>
  
  <pre><code>public static Func&lt;TEntity, object&gt; ValueUnTypedGetPropertyTypeFn(PropertyInfo pi)
  {
      var mi = typeof(StaticAccessors&lt;TEntity&gt;).GetMethod("TypedGetPropertyFn");
      var genericMi = mi.MakeGenericMethod(pi.PropertyType);
      var typedGetPropertyFn = (Delegate)genericMi.Invoke(null, new[] { pi });
  
      #if NO_EXPRESSIONS
      return x =&gt; typedGetPropertyFn.Method.Invoke(x, new object[] { });
      #else
      var typedMi = typedGetPropertyFn.Method;
      var obj = Expression.Parameter(typeof(object), "oFunc");
      var expr = Expression.Lambda&lt;Func&lt;TEntity, object&gt;&gt; (
              Expression.Convert(
                  Expression.Call(
                      Expression.Convert(obj, typedMi.DeclaringType),
                      typedMi
                  ),
                  typeof(object)
              ),
              obj
          );
      return expr.Compile();
      #endif
  }
  </code></pre>