title: Casting TResult in Task<TResult> to System.Object
body: <p>I am loading an assembly and calling a static method that will create a new object of type “MyClass1” (this type is specified at runtime) through reflection using MethodInfo.Invoke(). This works fine when the method is a normal sync method. However, the method being called is an async method which returns Task&lt;MyClass1>, which will be used to retrieve the result using task.Result.</p>
  
  <p>Ideally I should be using MyClass1 as TResult in the task, but the type is determined only at runtime so I can't do that. I am looking for a way to get the task and the result. I am trying to cast the TResult to System.Object and get the class as a generic Object. The following is the code I am using for this purpose.</p>
  
  <pre><code>public static void LoadAssembly()
  {
      // Calling static async method directly works fine
      Task&lt;MyClass1&gt; task1 = MyClass1.MakeMyClass1();
      MyClass1 myClass1 = task1.Result;
  
      // Calling static async method through reflection through exception.
      Assembly assembly = Assembly.LoadFrom(dllName);
      Type type = assembly.GetType("AsyncDll.MyClass1");
      var types = assembly.GetTypes(); 
      MethodInfo[] methodInfos = types[0].GetMethods(BindingFlags.Public | BindingFlags.Static);
      Type myClassType = types[0];
      MethodInfo mi = myClassType.GetMethod("MakeMyClass1");
      Object obj = Activator.CreateInstance(mi.ReflectedType);
      Task&lt;Object&gt; task = (Task&lt;Object&gt;)mi.Invoke(obj, null); // Exception occurs here.
      Object result = task.Result;
  }
  </code></pre>
  
  <p>Following is the method (test code) being called through reflection. This </p>
  
  <pre><code>public class MyClass1
  {
      public static async Task&lt;MyClass1&gt; MakeMyClass1()
      {
          MyClass1 newObject = null;
          await Task.Run(() =&gt;
          {
              newObject = new MyClass1();
          });
          return newObject;
      }
      ...
  }
  </code></pre>
  
  <p>Unfortunately, the casting of TResult is causing System.InvalidCastException.</p>
  
  <pre><code>An unhandled exception of type 'System.InvalidCastException' occurred in Test.exe
  
  Additional information: Unable to cast object of type 'System.Threading.Tasks.Task`1[MyClass1]' to type 'System.Threading.Tasks.Task`1[System.Object]'.
  </code></pre>
  
  <p>How can I cast the TResult in Task&lt;> to a generic object and get the result using task.Result? I would appreciate any help resolving this issue.</p>