Creating an object at runtime from type
Is it possible?
Let's say we have a list of objects. The list is of type 'parent class', but a number of 'child' classes are stored in the list.
Is there anyway to find the 'child class' type (using .GetType() ) and then use this Type to caste the list entry (of type 'parent class') into its original 'child class'?
Code examples that do not work..
Code:
foreach(baseclass bc in list)
{
Type derivedtype = bc.GetType();
//Here I can writline derivedtype .ToString() and get the name of the derived class, so seems to be holding it in there
//Then something like..
derivedtype derivedclassobject = new derivedtype () //Doesnt work
//or
bc = bc as derivedtype
//or
object o = (derivedtype )bc
//as well as things such using
Activator.CreateInstance(...);
}
Given that C# is strongly typed, is this possible at all? I have a work around for my program, but am interested to know if this is possible.
Is there anyway to create an object from its type at runtime?
Thanks
Re: Creating an object at runtime from type
Yes it is possible using the Activator.CreateInstance method.
Re: Creating an object at runtime from type
If possible, could you please show me a clear working example as I have had no luck at all
Re: Creating an object at runtime from type
Feels like doing homework here but what the heck :D
Code:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Stuff o;
o = (Stuff)Activator.CreateInstance(System.Type.GetType("ConsoleApplication1.Stuff"));
o.doStuff();
Console.ReadLine();
}
}
public class Stuff
{
public void doStuff()
{
Console.WriteLine("Do Stuff, created at Runtime");
}
}
}
Re: Creating an object at runtime from type
Hi Alsvha, many thanks for this, its going to be very useful!
I need to get home and experiment, however the thing I will be trying to do is create objects of an unknown type..i.e. "stuff" will hold type Type and that can vary.
I think i will have problems with this :( as c# is strongly typed
Thanks again, ill post my results here
Re: Creating an object at runtime from type
So, this is a really nasty thing to do and indicates a deeper design flaw in your program. Why can't you simply work through the base class (or explicit) interface? That is the question you should be asking, not how to cast yourself into unmaintainable code hell.