Upcasting in C#: 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/09 23:42 UTC
Read the original article Hit count: 131

Filed under:
|
|

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!

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET