title: Activator.CreateInstance() troubles
body: <p>I have a factory that is supposed to create objects that inherit from class Foo at run-time. I would think that System.Activator.CreateInstance's return type was the same as the type of an object it's creating, but judging from the following error message, its return type is Object.</p>
  
  <blockquote>
    <p>Error 1   Cannot implicitly convert type 'object' to 'cs_sandbox.Foo'. An explicit conversion exists (are you missing a cast?)    F:\projects\cs_sandbox\Form1.cs 46  24  cs_sandbox</p>
  </blockquote>
  
  <p>OK, so maybe I <em>am</em> missing a cast, but</p>
  
  <pre><code>return (t)System.Activator.CreateInstance(t);
  </code></pre>
  
  <p>results in yet another error message, which -- I must admit -- makes no sense to me:</p>
  
  <blockquote>
    <p>Error 1   The type or namespace name 't' could not be found (are you missing a using directive or an assembly reference?) F:\projects\cs_sandbox\Form1.cs 45  25  cs_sandbox</p>
  </blockquote>
  
  <p>And here's my code:</p>
  
  <pre><code>class Foo { }
  class FooChild1 : Foo { }
  class FooChild2 : Foo { }
  
  class MyFactory
  {
      public static Foo CreateInstance(string s)
      {
          Type t;
          if (s.StartsWith("abcdef"))
          {
              t = typeof(FooChild1);
              return System.Activator.CreateInstance(t);
          }
          else
          {
              t = typeof(FooChild2);
              return System.Activator.CreateInstance(t);
          }
      }
  }
  </code></pre>
  
  <p>How can I fix this code? Or, if it's not fixable, what are other ways of creating objects that inherit from a specific class at run-time?</p>