-5

i have one class named with Animal, with Name, Type, Gender, and i have another class named with AnimalList, i need to know how can i add Animals to my AnimalList, this is my class animal(im in console application): Filename Animal.cs

class Animal
{
  public string Name {get; set;}
  public string Type {get; set;}
  public string Gender {get; set;}

  public Person(string name, string type, string gender)
  {
       Name = name;
       Type = type;
       Gender = gender;
  }
}

And my class AnimalList: FilenameAnimalList.cs

class AnimalList: List<Animal>
{
     what should i do to add Animals to this list
}

shouldn't be better like this?

public new void Add(Animal value)
{
}
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Tiago
  • 1
  • 5
  • 2
    You need an instance of the list to add animals to it, at the moment you have two class definitions, these just describe the classes but don't utilise them in any way. Do you have a program (forms, wpf, console app etc)? – Charleh Apr 19 '16 at 08:31
  • `List` Already has the `.Add(T item)` therefor it would be pointless to create a method Add because you will have to specify the `new` BUT by doing that you will not have access to the internal structure of Add(T item). That would cause that you will not be able to store the `Animal value` in the internal structure of `List` – Donald Jansen Apr 19 '16 at 08:44
  • Working fiddle of how the code should be: https://dotnetfiddle.net/dkIEM5 – Draken Apr 19 '16 at 08:44
  • 2
    Also read the following, on StackOverFlow it is suggested not to inherit from List http://stackoverflow.com/questions/21692193/why-not-inherit-from-listt and also http://stackoverflow.com/questions/5376203/inheriting-from-listt/5376343#5376343 – Donald Jansen Apr 19 '16 at 08:46

3 Answers3

5

Why do you have the constructor for Person in your Animal class?

Do like this:

var animals = new AnimalList();
var animal = new Animal();
animals.Add(animal);

You have to make your Animal class public:

public class Animal
{
}
Wicher Visser
  • 1,513
  • 12
  • 21
3

Instantiate your AnimalList class somewhere(for example in main method) and then add the instances of an Animal class.

for example:

var animals = new AnimalList();

animals.Add(new Animal() {
   Name = "", 
   Type = "", 
   Gender = ""});
M.S.
  • 4,283
  • 1
  • 19
  • 42
error_handler
  • 1,191
  • 11
  • 19
0

First of all make your class Public And do this:

 AnimalList animalList = new AnimalList();
            Animal animal = new Animal();
            animal.Name = "x";
            animal.Type = "Y";
            animal.Gender = "M/F";
            animalList.add(animal);
NishantMittal
  • 537
  • 1
  • 4
  • 17