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();
}
}
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"});
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.