Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP C# Question: Making a Fruit a Pear

Tags:

c#

.net

oop

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?

like image 660
Adam Kane Avatar asked Nov 26 '22 22:11

Adam Kane


1 Answers

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.

like image 140
EMP Avatar answered Nov 29 '22 12:11

EMP