0

I'm a CS student and really don't know that much about coding so any help would be appreciated.

I've looked at many other examples of when this error is being thrown in other code- I understand that it occurs when an attempt is made to change the collection during iteration. But I'm not doing that; the PrevGen = NowGen; line is outside the foreach loop so I don't understand why it is throwing an error.

Code:

        int months = int.Parse(Console.ReadLine());
        Console.WriteLine("lifespan");
        int lifespan = int.Parse(Console.ReadLine());

        List<int> PrevGen = new List<int>{0};
        List<int> NowGen = new List<int>();
        Console.WriteLine(PrevGen.Count);

        for (int i = 0; i < months; i++)
        {
            foreach (int bunny in PrevGen)
            {
                if (bunny == 2 || bunny == 3)
                {
                    NowGen.Add(0);
                    if (bunny == 2) { NowGen.Add(bunny); }
                }
                else
                    NowGen.Add(bunny);
            }
            for (int x = 0; x <= NowGen.Count-1; x++)
            {
                NowGen[x]++;
            }
            Console.WriteLine(NowGen.Count);
            PrevGen = NowGen;

        }
    }
}

If anyone could help me as how to write the code so that prevGen can be modified & doesn't give an error, that would be great.

1 Answers1

1

The reason is here:

PrevGen = NowGen;

List<T> is a reference type, after that assignment PrevGen is referring NowGen instance. They become two variables that points to the same instance.

The error throws inside the foreach, because you are trying to add an item while enumerating the same instance.

My suggestion is to remove that line of code and instead replace all items inside PrevGen with the items contained into NowGen, for example:

PrevGen.Clear();
PrevGen.AddRange(NowGen);

Hope this help!

T-moty
  • 2,679
  • 1
  • 26
  • 31