title: Returning desired type from Activator.CreateInstance() instead of object
body: <p>I'm trying to create an instance of specified <code>Type</code> whatever user wants to have. For a quick illustration of my purpose please see the code below:</p>
  
  <pre><code>    static void Main(string[] args)
      {
          object o = GetInstance(typeof(int));
          Console.WriteLine("Created type: {0}", o.GetType().FullName);
      }
  
      public static object GetInstance(Type t)
      {
          Console.WriteLine("Creating instance of {0}", t.FullName);
          return Activator.CreateInstance(t);
      }
  </code></pre>
  
  <p>The problem is <code>Activator.CreateInstance()</code> returns <strong><code>object</code></strong> by default. There is also an overload of this method like <code>T Activator.CreateInstance&lt;T&gt;()</code> which is parameterless and returns the type you specify as <code>T</code>.</p>
  
  <p>However, the problem is <code>T</code> should be hard-coded while calling this method and thus should be a fixed value. I am trying to create an instance of desired class and return it as its type.</p>
  
  <p>Right now if you use this method you should write something like:</p>
  
  <pre><code>int i = GetInstance(typeof(int)) as int
  </code></pre>
  
  <p>I'm trying to reduce this to:</p>
  
  <pre><code>int i = GetInstance(typeof(int))
  </code></pre>
  
  <p>Is there a way that I can do casting inside the <code>GetInstance</code> and get rid of that <code>as int</code> repetition? By this way, my return type (and also the type I cast the object to) will be <em>unknown at compile time</em>.</p>
  
  <p>Seemed impossible by design to me but I'd really appreciate if you figure it out.</p>
  
  <p><strong>EDIT:</strong> Where I'm stuck is e.g. while you're casting, you can do <code>return (T) result</code> if you are in a generic method, but you can't do <code>Type t = ...; return (t) result</code> this doesn't work. You cannot cast to a type which is passed to you as a parameter <strong>which is not known at compile time</strong>.</p>