Click to See Complete Forum and Search --> : Collection of similar objects?


SilverTab
May 26th, 2008, 01:44 AM
Let's say I have a bunch of classes that inherits the "Animal" class (using a simple example so it's easier to explain)...

All my classes (ex: Gorilla, Dog etc..) have the Growl() method...

Is there a way I can hold a list or collection of "animals" (no matter if it's a dog or a gorilla) so I can do something like

animalList.Add(new Dog());
animalList.Add(new Gorilla());

and then call animalList[0].Growl();

Again, sorry for the stupid example, but I thought it would make my question easier to understand :)

I don't really mind if I have to use a Collection or a List or any other type of collection... as long as I can add different (but similar) objects to it, and call common methods on them...

hspc
May 26th, 2008, 02:05 AM
You can use generic collection as the List
for example:

List<Animal> animals = new List<Animal>();
animals.Add(new Dog());
animals.Add(new Cat());
foreach(Animal a in animals)
a.DoSomething();

SilverTab
May 26th, 2008, 02:11 AM
Awesome, thanks! Exactly what I needed...