-
December 13th, 2010, 06:28 AM
#1
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
-
December 13th, 2010, 06:49 AM
#2
Re: Creating an object at runtime from type
Yes it is possible using the Activator.CreateInstance method.
-
December 13th, 2010, 07:32 AM
#3
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
-
December 13th, 2010, 07:42 AM
#4
Re: Creating an object at runtime from type
Feels like doing homework here but what the heck
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");
}
}
}
-
December 13th, 2010, 09:32 AM
#5
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
-
December 13th, 2010, 01:49 PM
#6
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.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|