title: Create a Generic Func delegate using a runtime type
body: <p>I need to call a generic method that takes a generic Func as one of its parameters, where the Type parameter is known only at runtime. This part of the code is an object mapper, which maps properties between a source and a target object. ViewModelBase is the root of classes that are considered "target" objects.</p>
  
  <p>The method that I want to call (defined on ObjectMapperBuilder) has this signature:</p>
  
  <pre><code>public static ObjectMapperBuilder&lt;TTarget&gt; Create(
      Type sourceType, 
      MappingDirection direction, 
      Func&lt;TTarget, IDictionary&lt;String, object&gt;&gt; getDictionaryFromTarget = null
  );
  </code></pre>
  
  <p>In my base class, I want to call the above method, but use the most derived type as my type parameter:</p>
  
  <pre><code>public ViewModelBase {
      private ConcurrentDictionary&lt;string, object&gt; _propertyValues;
  
      public ViewModelBase (object sourceObject) {
          Type tTarget = this.GetType();
  
          // 1. How do I create the Func? All it does is return a private member.
          // This is wrong because it uses a compile-time generic parameter.
          Func&lt;TTarget,IDictionary&lt;String,object&gt;&gt; myFunc = (vm) =&gt; vm._propertyValues;
  
          // 2. Ho do I call the Create method using reflection to specify the 
          //    TTarget generic parameter at runtime?
          var myMapper = ObjectMapperBuilder&lt;TTarget&gt;.Create(
              sourceObject.GetType(), 
              MappingDirection.Bidirectional,
              myFunc
          );
          // Do stuff with myMapper.
          ...
      }
  </code></pre>
  
  <p>The purpose of this exercise is to be able to create the mapper in a method on the base class. The mapper must be created using the most derived type because I cache mappers according to source and target types, and different derived types need different mappers.</p>
  
  <p>This might be a job for Expression trees and Activator, but I can't figure it out.</p>
  
  <p>Part  of the answer might be found in the answer to this question:</p>
  
  <p><a href="https://stackoverflow.com/questions/658316/runtime-creation-of-generic-funct">Runtime creation of generic Func&lt;T&gt;</a></p>