title: Expression of type 'System.Int64' cannot be used for return type 'System.Object'
body: <p>I am trying to create an expression of the following form:</p>
  
  <pre><code>e =&gt; e.CreationDate;
  </code></pre>
  
  <p><code>CreationDate</code> is of type <code>long</code>, however I want the expression to return an <code>object</code> instead.</p>
  
  <p>I want to use <code>object</code> as a return type because the expression is built dynamically at runtime based on a query paramater. The query parameter specifies the property to access in the expression, such as:</p>
  
  <pre><code>&gt; entities?order=creationDate
  &gt; entities?order=score
  </code></pre>
  
  <p>As you can see, I can order by different properties with different types, so a return type <code>object</code> would allow me to build the expression as generic as possible.</p>
  
  <p>The problem is that when I try to create the expression:</p>
  
  <pre><code>ParameterExpression entityParameter = Expression.Parameter(typeof(Entity), "e");
  Expression propertyAccess = Expression.Property(entityParameter, property);
  Expression&lt;Func&lt;Entity, object&gt;&gt; result = Expression.Lambda&lt;Func&lt;Entity, object&gt;&gt;(propertyAccess, entityParameter);
  </code></pre>
  
  <p>I get the following exception:</p>
  
  <blockquote>
    <p>Expression of type 'System.Int64' cannot be used for return type
    'System.Object'</p>
  </blockquote>
  
  <p>It is strange, because as far as I know, all types extend from <code>object</code> (It seems polymorphism is not yet supported by expression trees).</p>
  
  <p>Nevertheless, I searched on the web and stumbled with this similar question: </p>
  
  <p><a href="https://stackoverflow.com/questions/2200209/expression-of-type-system-int32-cannot-be-used-for-return-type-system-object">Expression of type 'System.Int32' cannot be used for return type 'System.Object'</a></p>
  
  <p>Following <a href="https://stackoverflow.com/users/22656/jon-skeet">Jon Skeet</a>'s answer, I modified my last line to:</p>
  
  <pre><code>Expression&lt;Func&lt;Entity, object&gt;&gt; result = Expression.Lambda&lt;Func&lt;Entity, object&gt;&gt;(Expression.Convert(propertyAccess, typeof(object)), entityParameter);
  </code></pre>
  
  <p>This works fine, but it doesn't generate the expression I want. Instead, it generates something like this:</p>
  
  <pre><code>e =&gt; Convert(e.CreationDate)
  </code></pre>
  
  <p>I cannot use this solution, because later in the program an exception is thrown if the expression body is not a <code>MemberExpression</code> (i.e., a member access operation)</p>
  
  <p>I kept searching on the Internet for a satisfying answer, but couldn't find any.</p>
  
  <p>How can I achieve <code>e =&gt; e.CreationDate</code> where return type is <code>object</code>?</p>