Hello all,
I need to outline a little bit of background info for context. Please bear with me and I'll try to simplify my question as much as possible:
I have one object that inherits from another object. We'll call the first object Fruit and the second Apple. So I've declared Apple as follows:
public class Apple : Fruit
{
public string appleType;
public string orchardLocation;
// etc.
}
And the Fruit object as follows:
public class Fruit
{
public int fruitID;
public int price;
// etc.
}
So Apple inherits from Fruit. And let's say I have a number of other fruit types that all inherit from Fruit: Banana, Orange, Mango, etc.
In my application, I maintain the ability to store a particular type of fruit in the Session as that type's object, so I may have an Apple object in there or a Banana object. And I have a method that will retrieve the current Fruit from the session, written as follows:
protected Fruit GetModel(int fruitID)
{
// code to retrieve the fruit from the Session
// fruitID could be the ID for an Apple or Banana, etc.
}
Occasionally, I have a need to pull the fruit from the Session, update something about it, then upload it back into the Session. I may do this like this:
Apple myApple = (Apple)GetModel(fruitID);
myApple.orchardLocation = "Baugers";
UpdateModel(myApple); // just overwrites the current fruit in the Session
Now my question. I'm at a point where I need to pull the object from the Session, update something specific to the fruit itself (say, price), and then upload that same object back into the Session. Until now, I've always known the type of the object, so in my case now -- if I knew the fruit type -- I could just say:
Apple myApple = (Apple)GetModel(fruitID);
myApple.price = "4";
UpdateModel(myApple);
But this time, I'm trying to make it more generic to Fruit itself and don't always know the child type. And if I try to just pull the Fruit object itself from the Session (without casting), update it, and upload it back in, I've now just lost my child object (Apple) and only have a Fruit object in the Session. So I need a way to, generically, create a new instance of the type of object in the Session, update it, then upload it back in.
I know of a .NET method for Object called GetType() that returns a System.Type of the type of object you call it on, assuming that object inherits from Object. But I wasn't able to get very far with this, and I'd prefer not to have Fruit inherit from Object.
So I'll end with a pseudocode version of what I'd like:
public updateModelPrice(int price, fruitID)
{
FigureOutType fruit = (FigureOutType)GetModel(fruitID);
fruit.price = price;
UpdateModel(fruit);
}
Any help would be very much appreciated. Thanks.