H
HansHupe
Guest
It's probably a very simple question, but I am not sure how to design this class structure correctly. I have an abstract base class and two derived classes with different extended methods. In my application a List of Animals is stored. At some point in my code I select from this list explicitly one instance of the derived classes (animals[1]) which still has the type of the base class. So I get an error because the method of the derived class it not found.
What is a best practise to model this? I know I could define the fly() method already in Animal, but is this a correct way to do that?
public abstract class Animal
{
public Name string { get; set; }
}
public class Bird : Animal
{
public void fly(){Console.Write("I can fly");}
}
public class Dog : Animal
{
}
List<Animal> animals = new List<Animal>;
animals.Add(new Dog{Name = "Max"});
animals.Add(new Bird{Name = "Peter"});
animals[1].fly(); // Error
(Bird) animals[1].fly(); // Error
Continue reading...
What is a best practise to model this? I know I could define the fly() method already in Animal, but is this a correct way to do that?
public abstract class Animal
{
public Name string { get; set; }
}
public class Bird : Animal
{
public void fly(){Console.Write("I can fly");}
}
public class Dog : Animal
{
}
List<Animal> animals = new List<Animal>;
animals.Add(new Dog{Name = "Max"});
animals.Add(new Bird{Name = "Peter"});
animals[1].fly(); // Error
(Bird) animals[1].fly(); // Error
Continue reading...