DarkMalice
DarkMalice

Reputation: 205

C# Array Index Error

Simple array I'm adding to, however I keep getting this Index Out Of Bounds error. Looked around, can't quite figure out where I'm going wrong, I'm assuming it's something to do with where I've used the pos variable. Posted anything I think might be relevant. Thanks in advance.

const int MAX = 5;
    Account[] db = new Account[MAX];

    // global variable for position in array
    int pos;

    private void Form1_Load(object sender, EventArgs e)
    {
        // initialise the array with instantiated objects
        for (int i = 0; i < MAX; i++)
            db[i] = new Account();
    }

private void OpenAcc_Click(object sender, EventArgs e)
    {
        //hide menu
        hide_menu();

        //make new form elements visible
        tbNameEnt.Visible = true;
        tbBalaEnt.Visible = true;
        SubDet.Visible = true;

        //set pos to the first empty element of array
        pos = Array.FindIndex(db, i => i == null);
    }

private void SubDet_Click(object sender, EventArgs e)
    {
        string textBox1;
        double textBox2;
        int a = 0011228;
        int b = pos + 1;
        int accNo;

        //get and parse input details
        textBox1 = tbNameEnt.Text;
        textBox2 = double.Parse(tbBalaEnt.Text);

        //allocate account number
        accNo = int.Parse(a.ToString() + b.ToString());

        //set details for new object in array
        db[pos].SetAccount(textBox1, accNo, textBox2); //ERROR HERE

        //print account created confirmation message
        ConfMess();

        //OK button then takes us back to menu
    }

Upvotes: 2

Views: 1279

Answers (2)

ChenR
ChenR

Reputation: 161

you initialize your array with instantiated Account objects.

There's no guarantee the FindIndex() call would return a valid position (i.e pos would be assigned -1)

Following that, you might refer to db[-1], which would raise an exception.

Upvotes: 0

Habib
Habib

Reputation: 223237

Array.FindIndex would return position according to the predicate, if none of the item matched than it will return -1, For your case, you are assigning each element of the array in

for (int i = 0; i < MAX; i++)
       db[i] = new Account();

This will ensure that no item is null, hence -1 is returned from the Array.FindIndex, later when you use that position pos for accessing array element you get exception.

This line:

pos = Array.FindIndex(db, i => i == null);

Would set pos to -1 later when you do:

db[pos].SetAccount(textBox1, accNo, textBox2);

You will get exception.

Upvotes: 4

Related Questions