Pelicer Pelicer - 4 years ago 109
C# Question

IndexOutOfRange Exception Thrown on Setting Int value to Array

On my app a teacher can have several classes, and when I exclude a teacher's profile I have to, first, delete his classes. I'm trying to put each

class_id
of this teacher on an
int
array, to later delete all classes which the id is contained inside this array.

This is my code so far:

int x = 0;
int[] count = new int[x];

while (reader_SelectedClasses.Read())
{
if(x != 0)
{
x++;
count = new int[x];
}
count[x] = _class.Class_id = reader_SelectedClasses.GetInt16("class_id");
}


And this is what

reader_SelectedClasses.Read()


does:

select class_id from tbl_class where user_id = " + id + ";


And this is the return, when I try this on MySQL:

enter image description here

But it gives me back an IndexOutOfRangeException when I run the code on my DAO class. What am I missing? Already went here but didn't quite understand. Can someone please explain on few words and post and fixed code for this?

Answer Source
  1. You need to learn how to use a debugger and step through your program.

  2. count = new int[x]; discards what was in count and creates a new empty array that contains nothing. This array's indexes go from 0 to x - 1.

  3. count[x] = ... sets the array element at index x which according to the previous line is one past the end of the array.

You need to set count = new int[x] only once, at the beginning of your program, and set count[x] = ... only if x >= 0 and x < count.Length.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download