-1

I can't figure out why I'm getting this error, I spend like an hour looking at this code and nothing comes to my mind. " System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')' "

private void SetUpGame()
        {
            List<string> animalEmoji = new List<string>()
            {
                "", "",
                "", "",
                "", "",
                "", "",
                "", "",
                "","",
                "","",
                "","",
            };
            Random random = new Random();

            foreach (TextBlock textBlock in mainGrid.Children.OfType<TextBlock>())
            {
                int index = random.Next(animalEmoji.Count);
                string nextEmoji = animalEmoji[index];
                textBlock.Text = nextEmoji;
                animalEmoji.RemoveAt(index);
            }
        }
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Pnukso
  • 3
  • 2
  • Which line throws the exception? What are the runtime values of the variables on that line when it happens? – David Feb 16 '21 at 21:01
  • It trows on the "string nextEmoji = animalEmoji[index];" and I don't really know how to check runtime values – Pnukso Feb 16 '21 at 21:03
  • How many `TextBlock` instances are returned by `mainGrid.Children.OfType()`? – Joshua Robinson Feb 16 '21 at 21:03
  • 1
    @Pnukso: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/328193) Failing the use of a debugger, you can also log/output useful information in some way so that you can observe the resulting logged output and see what information was written. – David Feb 16 '21 at 21:05

1 Answers1

0

If you have more textBlocks in mainGrid.Children.OfType<TextBlock>() than you have emojis you will hit a point where you're all out of emojis and cannot access the 0th item with string nextEmoji = animalEmoji[index]; - your empty list (Count of 0) causes random.Next(0) to return 0, which then cannot be used as a list indexer

https://dotnetfiddle.net/yYH9ta

Caius Jard
  • 72,509
  • 5
  • 49
  • 80