Error C#: Index was out of range. Must be non-negative and less than the size of the collection

Vanessa Va picture Vanessa Va · Jun 14, 2016 · Viewed 7.2k times · Source

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();
    }
}

Answer

Patrick Hofman picture Patrick Hofman · Jun 14, 2016

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.