0

I've got a problem with creating objects in a for loop and adding them in a list. The program starts with "How much you want to add?" and whatever I write it shows me a message : Index was out of range. Must be non-negative and less than the size of the collection. What goes wrong? Sorry if there is another similar question but I couldn't find an answer. Thank you!

  using System;
using System.Collections.Generic;


class Animals
{

    public int id { get; set; }


    public string name { get; set; }


    public string color { get; set; }     


    public int age { get; set; }

    }

class Program
{
    static void Main(string[] args)
    {
        Console.Write("How much animals you want to add?: ");
        int count = int.Parse(Console.ReadLine());

        var newAnimals = new List<Animals>(count);

        for (int i = 0; i < count; i++)
        {
            newAnimals[i].id = i;

            Console.Write("Write name for animal " + i);
            newAnimals[i].name = Console.ReadLine();

            Console.Write("Write age for animal " + i);
            newAnimals[i].age = int.Parse(Console.ReadLine());

            Console.Write("Write color for animal " + i );
            newAnimals[i].color = Console.ReadLine();

        }

        Console.WriteLine("\nAnimals \tName \tAge \tColor");
        for (int i = 0; i < count; i++)
        {
            Console.WriteLine("\t" + newAnimals[i].name + "\t" + newAnimals[i].age + "\t" + newAnimals[i].color);
        }

        Console.ReadLine();
    }
}
Vanessa Va
  • 21
  • 1
  • 1
  • 3
  • If you know the initial (and final) size you could also use an `Animals[]`. Then you could initialize the array in your way (via index). If the size could change later you should use the `List` and `List<>.Add` to add elements. – Tim Schmelter Jun 14 '16 at 13:05

2 Answers2

3

Since you didn't add any items to your list newAnimals, it is empty, and thus it has no item on index 0.

Create an instance of Animal and then Add it (I renamed the class name, since it is a singular):

Animal animal = new Animal();

// do you magic

newAnimals.Add(animal);

After this, you can retrieve the item at index 0.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
2

var newAnimals = new List<Animals>(count); creates an empty list with specific Capacity (the total number of elements the internal data structure can hold without resizing)

As it says in MSDN about this constructor:

Initializes a new instance of the List class that is empty and has the specified initial capacity.

You need to use Add method to add elements to the list.

newAnimals.Add (new Animal() {id = 1, name = "name"});
Valentin
  • 5,380
  • 2
  • 24
  • 38