-1

I am trying to create objects and add them to a list. But I keep getting error : Argument Out Of Range Exception for loop condition I am new to Visual Studio and C# so I am not sure what is the problem in my code. In Java this is how you would create in a for loop objects and I don't see why the condition of the for loop is wrong.

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

        var newPersons = new List<Person>(count);

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

            Console.Write("Write name for person " + i);
            newPersons[i].name = Console.ReadLine();

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

            Console.Write("Write adress for person " + i);
            newPersons[i].adress = Console.ReadLine();

        }

        Console.WriteLine("\nPersons \tName \tAge \tAdress");
        for (int i = 0; i < count; i++)
        {
            Console.WriteLine("\t" + newPersons[i].name + "\t" + newPersons[i].age + "\t" + newPersons[i].adress);
        }

        Console.ReadKey();
    }



 class Person
{
    //Person object id
    public int id { get; set; }

    //Persons name
    public string name { get; set; }

    //Persons adress
    public string adress { get; set; }

    //Persons age
    public int age { get; set; }

}
  • 1
    What line does this error refer to? What input do you use to produce this error? – Scott Hunter Jun 03 '21 at 12:06
  • 1
    Since you are using List<> you don't have to create a certain count ahead of time. Just use newPersons.Add(). – Terry Tyson Jun 03 '21 at 12:07
  • 2
    The line of code … `var newPersons = new List(count);` … is not doing what you think it is doing. Put a break point on the `for` loop and you will see `newPersons` has a size of zero. – JohnG Jun 03 '21 at 12:12
  • 1
    You have misunderstood what the [`List` constructor accepting a capacity parameter](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.-ctor?view=net-5.0#System_Collections_Generic_List_1__ctor_System_Int32_) does. It only specifies an internal capacity; it doesn't make the list have that many elements. `Capacity` is how much room the list currently has for elements (this can be expanded). `Count` is the actual number of elements in use. – Matthew Watson Jun 03 '21 at 12:14
  • See [List.Capacity Property](https://learn.microsoft.com/dotnet/api/system.collections.generic.list-1.capacity) –  Jun 03 '21 at 12:14
  • Defining the length of a list when you know it ahead of time is a good practice, but a bit misleading. You should be using `.Add()`. – Mariano Luis Villa Jun 03 '21 at 12:14

3 Answers3

0

List<> allows you to add elements dynamically without specifying a size ahead of time. Then you use .Add to add the elements. Change your code as follows:

var newPersons = new List<Person>(count);

        for (int i = 0; i < count; i++)
        {
            Person person = new Person();
            person.id = i;

            Console.Write("Write name for person " + i);
            person.name = Console.ReadLine();

            Console.Write("Write age for person " + i);
            person.age = int.Parse(Console.ReadLine());

            Console.Write("Write adress for person " + i);
            person.adress = Console.ReadLine();

            newPersons.Add(person);
        }
Terry Tyson
  • 629
  • 8
  • 18
0
var newPersons = new List<Person>(count);

That creates a List of Persons, with an initial capacity of count items. However it doesn't actually add any items to the list, you need to do that yourself. If you know how many items you'll ultimately add it's good practise to create the list at the right size ahead of time.

for (int i = 0; i < count; i++)
{
    newPersons.Add(new Person());
    ...

This will add a new Person to the List, and allow the rest of the code to work.

BTW, when iterating though an existing list I prefer to use the foreach:

foreach (Person thisPerson in newPersons)
{
    Console.WriteLine("\t" + thisPerson.name + "\t" + thisPerson.age + "\t" + thisPerson.adress);
}

To me that's more concise.

Slugsie
  • 851
  • 1
  • 7
  • 17
0

Here you have two options -

  1. You can create a array instead of list and create an object and assign the value.

     var newPersons = new Person[count];
     for (int i = 0; i < count; i++)
     {
     newPersons[i] = new Person(); //This is an extra line I have added
     newPersons[i].id = i;
    
     Console.Write("Write name for person " + i);
     newPersons[i].name = Console.ReadLine();
    
     Console.Write("Write age for person " + i);
     newPersons[i].age = int.Parse(Console.ReadLine());
    
     Console.Write("Write adress for person " + i);
     newPersons[i].adress = Console.ReadLine();
    
     }
    
  2. You can use list. List allow you to dynamically add the item on it. So you dont need to decide list size at first place.

     var newPersons = new List<Person>();
     for (int i = 0; i < count; i++)
     {
     Person per = new Person();
     per.id = i;
    
     Console.Write("Write name for person " + i);
     per.name = Console.ReadLine();
    
     Console.Write("Write age for person " + i);
     per.age = int.Parse(Console.ReadLine());
    
     Console.Write("Write adress for person " + i);
     per.adress = Console.ReadLine();
    
     newPersons.Add(per);
     }
    
Amit Gupta
  • 252
  • 3
  • 8