Extending objects at runtime

G

Guest

Hi,

I've been trying to figure this out for a while and can't find the answer.
For simplicity I will use a basic example rather than my real classes.

I have one base class, Item and various extended classes which inherit from
Item, ExtendedItem1, ExtendedItem2, etc. As expected, Item defines properties
and methods common to all items. The ExtendedItem classes define additional
properties and methods specific to different types of items.

At runtime, I create an instance of an Item. Depending on certain
conditions, I want to extend that Item into one of the ExtendedItem classes,
ie transform the Item object into an ExtendedItem1 or ExtendedItem2 object.

Is there an easy way to do this? Can I easily tell the ExtendedItem class to
use my already instanciated Item object as the base class? or do I have to
write a new constructor for each ExtendedItem class that accepts an Item
object and itializes all values in the base class to those in the Item object
parameter?

Any help is appreciated.

Thanks,

James
 
T

Tim Mulholland

As far as i know, you need to write a constructor for your Extended classes
that takes an instance of Item and sets the properties correctly as you
suggested. I don't think there's any other way to upcast. Though someone
else might know some workaround.

-Tim
 
?

=?iso-8859-1?Q?Anders=20Nor=e5s?=

I have one base class, Item and various extended classes which inherit
from Item, ExtendedItem1, ExtendedItem2, etc. As expected, Item
defines properties and methods common to all items. The ExtendedItem
classes define additional properties and methods specific to different
types of items.

At runtime, I create an instance of an Item. Depending on certain
conditions, I want to extend that Item into one of the ExtendedItem
classes, ie transform the Item object into an ExtendedItem1 or
ExtendedItem2 object.

Use your Item class as a constructor argument to your ExtendedItem classes
as shown below:
public class MyClass
{
public static void Main()
{
Item myItem=new Item();
myItem.MyItemField="Hello world!";
ExtendedItem myExtendedItem=new ExtendedItem(myItem);
// Writes Hello World!
Console.WriteLine(myExtendedItem.MyItemField);
}
}

public class Item
{
public string MyItemField;
}
public class ExtendedItem : Item
{
public string MyExtendedItemField;
public ExtendedItem(Item item)
{
this.MyItemField=item.MyItemField;
}
}

Regards,
Anders Norås
http://dotnetjunkies.com/weblog/anoras/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top