John
John

Reputation: 659

Call object specific method from abstract list in C#

I have a list of abstract classes like

List<Animal> animalList = new List<Animal>();

I iterate over the list by doing

foreach(Animal a in animalList.Values){
  if(a is Monkey){
    //Call monkey specific method
    a.PeelBanana() //This is essentially what I would like to be able to do
  }
  else if(a is Giraffe){
    //Call a method specific to Giraffe
  }

}

So the animals share common functionality such as eat() and sleep() but what I am wondering is if there is way to call, for example, PeelBanana() from the monkey class, a method which does not exist in all derivations of the Animal class.

Upvotes: 2

Views: 113

Answers (2)

MAV
MAV

Reputation: 7457

I would suggest that you make Animal an abstract class and make Monkey, Giraffe and other animals implement common methods. It could look something like this:

public abstract class Animal
{
    public abstract void Eat();
    ...
}
public class Giraffe : Animal
{
    public override void Eat()
    {
        // Giraffe eating
    }
    ...
}
public class Monkey : Animal
{
    public override void Eat()
    {
        this.PeelBanana();
        this.EatBanana();   //Or something like this
    }
    ...
}

And then just do

foreach(Animal a in animalList.Values){
    a.Eat();
}

This is a much more object-oriented way of solving this.

Upvotes: 4

Ant P
Ant P

Reputation: 25221

You'll have to cast it first:

if(a is Monkey){
    ((Monkey)a).PeelBanana();
}

Be careful with this, though; if you find yourself having to cast objects like this there are probably flaws in your approach. Strictly speaking, if you are working with a List<Animal>, then all you should care about is the behaviour defined in Animal.

Upvotes: 3

Related Questions