user961437
user961437

Reputation:

Why is this causing an 'Index out of range' exception?

    public void button2_Click(object sender, EventArgs e)

    {
        char[] delimiters = { ',', '\r', '\n', ' ' };
        string[] content = File.ReadAllText(CSV_File).Split(delimiters);

        int bounds = (content.GetUpperBound(0)); //bounds of this content string is 96
        int i = 1;
        id = new string[(bounds / 4)]; //for example index size = 96 / 4 = 24

        for (i = 0; i <= (bounds / 4); i++)
        {
            int rows = (i * 4); // gets every 4th value
            id[i] = content[rows]; //inserts row 96 into id 24 - fails here
        }
    }

Stuck on this for a while now. The exact error is "Index was outside the bounds of the array". I do not know to which index this refers however.

Upvotes: 1

Views: 1065

Answers (5)

Scott Smith
Scott Smith

Reputation: 1863

For best coding practices, it would be better to check against id.Length in the for loop instead of checking against bounds / 4.

With that said, I believe you should be using < instead of <= in your conditional statement in the for loop.

Upvotes: 1

YellPika
YellPika

Reputation: 2902

Looks like you accidentally wrote <= instead of <. Remember that array indices go up to the length - 1.

I might recommend cleaning up the code a bit. That's a lot of extra brackets and variables...

var delimeters = new[] { ',', '\r', '\n', ' ' };
var content = File.ReadAllText(CSV_File).Split(delimeters);

id = content.Where((n, i) => i % 4 == 0).ToArray();

Upvotes: 1

Marlon
Marlon

Reputation: 20312

I believe on the last iteration you will get the exception, because on the last iteration you are accessing index (bounds / 4), but the valid range of indexes are 0 to (bounds / 4 ) - 1. Basically, you are going one past the end of your array id. You need to change the <= to a < in your loop condition.

Upvotes: 0

Justin Self
Justin Self

Reputation: 6265

Change the <= to < in the for loop.

Upvotes: 3

WoLfulus
WoLfulus

Reputation: 1977

This depends on the content of the file you are actually reading. The code seems fine.

Upvotes: 1

Related Questions