What i’m tring to do is this.
I have a Inheritance tree that looks something like this
BaseType
BaseType : DerType1
BaseType : DerType2
BaseType : DerType3
so first i’ve declare a variable of type BaseType to be used
BaseType b;
Any of the derived types can be read in as a string
so i’ve got an instance creator something like
object o = Activator.CreateInstance(Type.GetType(readValue));
What i then want to do is assign this new object to B
Something like
b = o //Doesn't work obviously because of casting rules
b= (DerType1)o; //works
but i can’t figure out how to dynamically retype the intended cast
b = (o.GetType())o; //what i want but can't be done like this
maybe there’s a trick with using generics i’m not thinking about?
I found an article talking about doing it something like this with generics
public T GetInstance<T>(string type) where T: new()
{
return (T)Activator.CreateInstance(Type.GetType(typeName));
}
but it seems to me that i still will need to statically reference the type name in the call to this method
b = GetInstance<DerType1>("DerType1")
b = GetInstance<DerType2>("DerType2")
b = GetInstance<DerType3>("DerType3")
thanks for the ideas.
Maybe i should be taking a whole new, better approach?
Also maybe i’m just not paying attention as
b = (BaseType)Activator.CreateInstance(Type.GetType(typeName));
seems to be helpful
Why not just declare:
as
Then you could do: