Let's say I have a collection of objects that all inherit from a base class. Something like...
abstract public class Animal
{
}
public class Dog :Animal
{
}
class Monkey : Animal
{
}
Now, we need to feed these animals, but they are not allowed to know how to feed themselves. If they could, the answer would be straightforward:
foreach( Animal a in myAnimals )
{
a.feed();
}
However, they can't know how to feed themselves, so we want to do something like this:
class Program
{
static void Main(string[] args)
{
List<Animal> myAnimals = new List<Animal>();
myAnimals.Add(new Monkey());
myAnimals.Add(new Dog());
foreach (Animal a in myAnimals)
{
Program.FeedAnimal(a);
}
}
void FeedAnimal(Monkey m) {
Console.WriteLine("Fed a monkey.");
}
void FeedAnimal(Dog d)
{
Console.WriteLine("Fed a dog.");
}
}
Of course, this won't compile, as it would be forcing a downcast.
It feels as if there's a design pattern or some other solution with generics that help me out of this problem, but I haven't put my fingers on it yet.
Suggestions?