title: Casting a Delegate into an Action<T> or Func<T> in runtime
body: <p>I'm trying to improve my reflection code by creating Delegates for the <code>Getter</code> and <code>Setter</code> methods.</p>
  
  <p>My code looks like this:</p>
  
  <pre><code>MyObject obj = new MyObject();
  var prop = obj.GetType().GetProperty("Prop");
  var getType = typeof(Func&lt;&gt;).MakeGenericType(prop.PropertyType);
  var setType = typeof(Action&lt;&gt;).MakeGenericType(prop.PropertyType);
  
  var getMethod = prop.GetGetMethod().CreateDelegate(getType, obj);
  var setMethod = prop.GetSetMethod().CreateDelegate(setType, obj);
  
  // I'd like to change this section and not to use a dynamic!!
  dynamic castedGet = Convert.ChangeType(getMethod, getType);
  dynamic castedSet = Convert.ChangeType(setMethod, setType);
  </code></pre>
  
  <p><code>CreateDelegate</code> returns a <code>Delegate</code> and using <code>DynamicInvoke</code>  <strong>isn't</strong> performance wise.</p>
  
  <p>I casted (hardcoded) the <code>Delegate</code> into <code>Action&lt;T&gt; \ Func&lt;T&gt;</code> and saw a huge increase in my performance.</p>
  
  <p>I then tried to cast the <code>Delegate</code> into <code>Action&lt;T&gt; \ Func&lt;T&gt;</code> in runtime (using <code>Convert.ChangeType</code> and <code>dynamic</code>) and my performance got hurt - probably due to the fact that I'm using a <code>dynamic</code> type.</p>
  
  <p>I'm pretty sure that I can do this without <code>dynamic</code>.<br/></p>
  
  <p>I <strong>guess</strong> the solution has something to do with <code>expression trees</code>, but I'm not really sure how to code something like this. If someone has a good solution that doesn't use <code>expression trees</code> than it will be interesting to hear about it as well.</p>