0

I've created a class "Person" and I want to do a while loop to let the user add objects until they want to stop, but it doesn't work.

I think the problem is I don't know how to create new objects from a list, but I'm unsure.

Here's my code:

static void Afficher(List <Personne> maliste)
{
    foreach (var per in maliste)
    {
        per.ToString();
    }
}

static void Ajouter(List<Personne> maliste)
{
    string s;
    bool stop = false;
    int i = 0;
    while(!stop)
    {
        Console.WriteLine("Entrez les informations ou entrez pour terminez!!");
        Console.WriteLine("Entrez le nom de la personne numero "+ (i+1));
        s = Console.ReadLine();
        if (s == "") break;
            maliste[i] = new Personne();
            maliste[i].nom = s;
            Console.WriteLine("Entrez le prenom de la personne numero " + (i + 1));
            s = Console.ReadLine();
        if (s == "") break;
            maliste[i].prenom = s;
            Console.WriteLine("Entrez l'age de la personne numero " + (i + 1));
            s = Console.ReadLine();
        if (s == "") break;
            maliste[i].age = int.Parse(s);

        i++;
    }
}

Error happens on maliste[i] = new Personne(); line:

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

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • *Somewhere* based on something you will want to set `stop` to true to break out of the loop. You will also want to be much, much clearer about `it doesn't work` – Ňɏssa Pøngjǣrdenlarp Mar 08 '19 at 23:47
  • @MakeStackOverflowGoodAgain no, they have `break` in several mis-formatted `if` checks - so all good (`while(true)` would be better, but...) – Alexei Levenkov Mar 09 '19 at 02:45

1 Answers1

2

You can't use the array indexing (like maliste[i]) when adding a new item. All you need to do is call maliste.Add to insert a new item in the list. Your function should look like this:

static void Ajouter(List<Personne> maliste)
{
    string s;
    bool stop = false;
    int i = 0;
    while(!stop)
    {
        Console.WriteLine("Entrez les informations ou entrez pour terminez!!");
        Console.WriteLine("Entrez le nom de la personne numero "+ (i+1));
        s = Console.ReadLine();
        if (s == "") break;
            var pers = new Personne();
            maliste.Add( pers );
            pers.nom = s;
            Console.WriteLine("Entrez le prenom de la personne numero " + (i + 1));
            s = Console.ReadLine();
        if (s == "") break;
            pers.prenom = s;
            Console.WriteLine("Entrez l'age de la personne numero " + (i + 1));
            s = Console.ReadLine();
        if (s == "") break;
            pers.age = int.Parse(s);

        i++;
   }
}
Darrin Cullop
  • 1,170
  • 8
  • 14