Upcasting in C#: Making a Fruit a Pear
- by Adam Kane
Why can't I upcast (?) a Fruit to a Pear?
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!