-1

This error is appearing when it reaches the classes[0].AddLesson(one); line and I have no idea why this is happening? any ideas would be great... I have two classes btw Lesson and Timetable

   List<Timetable> classes = new List<Timetable>();
    private void Form1_Load(object sender, EventArgs e)
    {
        
        Lesson one = new Lesson("maths", 1, 2);
        Lesson two = new Lesson("science", 3, 4);
        classes[0].AddLesson(one);
        classes[1].AddLesson(two);

        DisplayList(classes);

    }

    void DisplayList(List<Timetable> timetable)
    {
        lstTimetable.Items.Clear();
        foreach(Timetable t in timetable)
        {
            lstTimetable.Items.Add(t);
        }
    }
Kube
  • 9
  • 3
  • 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) – Selvin Oct 12 '20 at 10:20
  • classes.Add(one); Use this instead of classes[0].AddLesson(one); – Ajoe Oct 12 '20 at 10:44

2 Answers2

-1

The list is empty, so you first have to assign values to the list. If you replace

classes[0].AddLesson(one);

with

classes.Add(one);

It should work.

Source

Daantje
  • 7
  • 1
-2

You have created a new list here:

List<Timetable> classes = new List<Timetable>();

But you haven't added anything to that list so it had no length (zero indexes). When you try to assign a value to the first index of the list here:

classes[0].AddLesson(one);

You're getting the exception because index 0 doesn't exist.

If you want to add to a list you do:

classes.Add(one);

WSC
  • 903
  • 10
  • 30