title: Function returning a generic type whose value is known only at runtime
body: <p>I need to use a generic interface like the following:</p>
  
  <pre><code>public interface IContainer&lt;T&gt;
  {
      IEnumerable&lt;IContent&lt;T&gt;&gt; Contents { get; }
  }
  </code></pre>
  
  <p>An object implementing this interface is returned by a generic method like the following:</p>
  
  <pre><code>IContainer&lt;T&gt; GetContainer&lt;T&gt;(IProperty property);
  </code></pre>
  
  <p>Type <code>T</code> is unknown until run-time.</p>
  
  <p>Using reflection I am able to invoke the <code>GetContainer&lt;T&gt;</code> method and get the result. </p>
  
  <p>My problem is that I don't know how to enumerate the result which has type <code>Object</code> (therefore I cannot cast it to <code>IEnumerable</code>).</p>
  
  <p>I have also tried casting as follows but it does not work (it says "Type is expected"):</p>
  
  <pre><code>var myContainer = genericMethodInfo.Invoke(
                             myService, 
                             new object[] { property })
      as typeof(IContainer&lt;&gt;).MakeGenericType(type);
  </code></pre>
  
  <p>where <code>type</code> is the runtime type, <code>myService</code> is the service exposing the <code>GetContainer&lt;T&gt;</code> method, and <code>property</code> is of type <code>IProperty</code> as needed. </p>
  
  <p><strong>UPDATE</strong>: see my complete solution in my blog: <a href="http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/" rel="nofollow noreferrer">http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/</a></p>