|
-
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
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
|