|
-
May 26th, 2008, 01:44 AM
#1
Collection of similar objects?
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...
-
May 26th, 2008, 02:05 AM
#2
Re: Collection of similar objects?
You can use generic collection as the List
for example:
Code:
List<Animal> animals = new List<Animal>();
animals.Add(new Dog());
animals.Add(new Cat());
foreach(Animal a in animals)
a.DoSomething();
-
May 26th, 2008, 02:11 AM
#3
Re: Collection of similar objects?
Awesome, thanks! Exactly what I needed...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|