polymorphism pass instantiated base to deriver
Posted
by Eric
on Stack Overflow
See other posts from Stack Overflow
or by Eric
Published on 2010-03-23T18:34:22Z
Indexed on
2010/03/23
18:43 UTC
Read the original article
Hit count: 297
I was wondering how to do this, consider the following classes
public class Fruit
{
public string Name { get; set; }
public Color Color { get; set; }
}
public class Apple : Fruit
{
public Apple()
{
}
}
How can I instantiate a new fruit but upcast to Apple, is there a way to instantiate a bunch of Fruit and make them apples with the name & color set. Do I need to manually deep copy?
Of course this fails
Fruit a = new Fruit();
a.Name = "FirstApple";
a.Color = Color.Red;
Apple wa = a as Apple;
System.Diagnostics.Debug.Print("Apple name: " + wa.Name);
Do I need to pass in a Fruit to the AppleCTor and manually set the name and color( or 1-n properties) Is there an better design to do this?
© Stack Overflow or respective owner