dynamically creating objects from string to derived types
<p>What i'm tring to do is this.</p>

<p>I have a Inheritance tree that looks something like this</p>

<pre><code>BaseType
BaseType : DerType1
BaseType : DerType2
BaseType : DerType3
</code></pre>

<p>so first i've declare a variable of type <code>BaseType</code> to be used</p>

<pre><code>BaseType b;
</code></pre>

<p>Any of the derived types can be read in as a string </p>

<p>so i've got an instance creator something like </p>

<pre><code>  object o =  Activator.CreateInstance(Type.GetType(readValue));
</code></pre>

<p>What i then want to do is assign this new object to <code>B</code></p>

<p>Something like </p>

<pre><code>b = o //Doesn't work obviously because of casting rules
b= (DerType1)o; //works 
</code></pre>

<p>but i can't figure out how to dynamically retype the intended cast</p>

<pre><code>b = (o.GetType())o; //what i want but can't be done like this
</code></pre>

<p>maybe there's a trick with using generics i'm not thinking about? </p>

<p>I found an article talking about doing it something like this with generics</p>

<pre><code>public T GetInstance&lt;T&gt;(string type) where T: new()
        {
            return (T)Activator.CreateInstance(Type.GetType(typeName));
        } 
</code></pre>

<p>but it seems to me that i still will need to statically reference the type name in the call to this method</p>

<pre><code>b  = GetInstance&lt;DerType1&gt;("DerType1")
b  = GetInstance&lt;DerType2&gt;("DerType2")
b  = GetInstance&lt;DerType3&gt;("DerType3")
</code></pre>

<p>thanks for the ideas.</p>

<p>Maybe i should be taking a whole new, better approach?
Also maybe i'm just not paying attention as</p>

<pre><code>b = (BaseType)Activator.CreateInstance(Type.GetType(typeName));
</code></pre>

<p>seems to be helpful</p>
