-1

I do not understand why this for loop is throwing exception. starting index is 0 and and index of inputStringArray is 4 so I really do not get it.

    Console.WriteLine("please enter several numbers separated by hyphen");

    var input = Console.ReadLine();
    var inputStringArray = input.Split('-');
    var listOfNumbers = new List<int>();

    for (int i = 0; i < inputStringArray.Length; i++)
    {
        listOfNumbers[i] = Convert.ToInt32(inputStringArray[i]);
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Alex M
  • 11
  • 2
  • 1
    Does this answer your question? [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Yong Shun Aug 07 '21 at 07:11

1 Answers1

2

The problem is with the List, not with the array.

//listOfNumbers[i] = Convert.ToInt32(inputStringArray[i]);
  listOfNumbers.Add(Convert.ToInt32(inputStringArray[i]));
H H
  • 263,252
  • 30
  • 330
  • 514
  • 1
    Yup. When this program starts, listOfNumbers has 0 items, and you cannot index items in a List object that aren't there. You need to add items to the list with the .Add method. – TomXP411 Aug 07 '21 at 07:19
  • And a little bit optimization: specify the capacity of this list, if you know how many elements are expected: `var listOfNumbers = new List(inputStringArray.Length);` – Steeeve Aug 07 '21 at 12:08