OutOfRangeException error when the array has items in it?

77 views Asked by At

I have 3 classes and they more or less go like this:

Class a

class a {
    b bObject;
    public a() {

    }
    protected override void Draw(GameTime gameTime) {
        bObject = new b(); // I know this is bad but I need this here
        spriteBatch.Begin();
        b.DrawFunction();
        spriteBatch.End();
    }
}

Class b

class b {
    List<c> cList = new List<c>();
    int itemAtIndex10;
    public b() {
        for(int i = 0; i < 32; i++) {
            cList.Add(new c { bunch of variables here }); // 32 items in the list
        }
    }
    public void DrawFunction() {
        spriteBatch.Draw(drawstuff);

        // more code

        itemAtIndex10 = cList[10].variable; // This causes an OutOfRangeException?
    }
}

Class c

class c {
    // Loads of variables here
    public c() {

    }
}

Why does this cause an OutOfRangeException? The error is telling me it's coming from "cList" even though in class b, I've added 32 items.

3

There are 3 answers

2
Rob Stewart On

I think this line...

cList.Add(new cList { bunch of variables here }); // 32 items in the 

Should be this line...

cList.Add(new c { bunch of variables here }); // 32 items in the 

unless i'm mistaken cList is a List, where c is the class c from below.

1
Piotr M On

cList.Add(new cList { bunch of variables here });

Looks like cList has 1 element cList. So acess should be like

var x = cList[0]

and then

itemAtIndex10 = x[10]

Edit : My bad, did not spotted this is loop. I will not delete it, but it is correct answer, sorry :/

3
Steven Cowles On

Try changing

public class b() {

to

public b() {

As what you're doing currently is creating a second class called b within your b class, rather than creating a constructor for b.

That said - I have no idea how you managed to get

cList.Add(new cList { bunch of variables here });

to even compile.