title: How to create the return type of a method which returns Task<T> using Reflection?
body: <p>We have a class with a number of sync and async methods that return <code>Response&lt;T&gt;</code> and <code>Task&lt;Response&lt;T&gt;&gt;</code> respectively.</p>
  <p>Our program is such that we use reflection to <code>invoke</code> the desired method using the <code>MethodInfo</code> that reaches to us but before actually invoking the method, a series of checks should be applied and therefore <code>Error</code> property of <code>Response&lt;T&gt;</code> should be set beforehand (if checks fail) (<em>codes are just as example</em>).</p>
  <pre><code>public class Test
  {
      public Response&lt;int&gt; GetAge()
      {
          return new Response&lt;int&gt;() { Error = null, Result = 10 };
      }
      
      public async Task&lt;Response&lt;int&gt;&gt; GetAgeAsync()
      {
          return new Response&lt;int&gt;() { Error = null, Result = 10 };
      }
  }
  
  public class Response&lt;T&gt;
  {
      public string? Error { get; set; }
      public T Result { get; set; }
  }
  </code></pre>
  <p>Creating the return type of sync methods is working fine:</p>
  <pre><code>public void Execute(MethodInfo? methodInfo, object?[]? parameters) //from: typeof(Test).GetMethod(&quot;GetAge&quot;);
  {
      dynamic response = Activator.CreateInstance(methodInfo.ReturnType);
      
      //some checks...
      
      response.Error = &quot;not allowed.&quot;;
      //no need for: methodInfo.Invoke(typeof(Test), parameters);
  }
  </code></pre>
  <p>but if the return type of method is <code>Task&lt;T&gt;</code> (in this example: <code>Task&lt;Response&lt;int&gt;&gt;</code>), the <code>Activator.CreateInstance</code> complains:</p>
  <pre><code>Unhandled exception. System.MissingMethodException: No parameterless constructor defined for type 'System.Threading.Tasks.Task`1[ConsoleApp.Re
  sponse`1[System.Int32]]'.
  </code></pre>
  <p>The important point is that we are not allowed to change the return type of methods and we are only allowed to set the value of <code>Error</code> property.</p>