OOP C# Question: Making a Fruit a Pear
Posted
by Adam Kane
on Stack Overflow
See other posts from Stack Overflow
or by Adam Kane
Published on 2010-06-09T23:34:25Z
Indexed on
2010/06/10
0:02 UTC
Read the original article
Hit count: 251
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 simple 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?
© Stack Overflow or respective owner