CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    May 2008
    Posts
    27

    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...

  2. #2
    Join Date
    Apr 2002
    Location
    Egypt
    Posts
    2,210

    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();
    Hesham A. Amin
    My blog , Articles


    <a rel=https://twitter.com/HeshamAmin" border="0" /> @HeshamAmin

  3. #3
    Join Date
    May 2008
    Posts
    27

    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
  •  





Click Here to Expand Forum to Full Width

Featured