Given that I have an instance of Fruit with some properties set, and I want to get those properties into a new Pear instance (because this particular Fruit happens to have the qualities of a pear), what's the best way to achieve this effect?
For example, what we can't do is simply cast a Fruit to a Pear, because not all Fruits are Pears:
public static class PearGenerator {
public static Pear CreatePear () {
// Make a new generic fruit.
Fruit genericFruit = new Fruit();
// Upcast it to a pear. (Throws exception: Can't cast a Fruit to a Pear.)
Pear pear = (Pear)genericFruit;
// Return freshly grown pear.
return ( pear );
}
}
public class Fruit {
// some code
}
public class Pear : Fruit {
public void PutInPie () {
// some code
}
}
Thanks!
Update:
I don't control the "new Fruit()" code. My starting point is that I've got a Fruit to work with. I need to get that Fruit into a new Pear somehow. Maybe copy all the properties one by one?
Because the Fruit you've created isn't a Pear!
Edit: If you already have a Fruit
and need to create a Pear
from it then yes, you have no choice but to copy all the properties to a new Pear object. This should ideally be done inside a Pear
constructor that you create especially for that purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With