topofsteel
topofsteel

Reputation: 1277

array with 1 element causing error in for loop

I'm using the array length as the test condition in my for loop. But if there is only one element in the array, I receive an 'Index was outside the bounds of the array' error. What am I doing wrong? Thanks.

string templateList;
string[] template;

string sizeList;
string[] size;

templateList = textBox1.Text;
template = templateList.Split(',');

sizeList = textBox2.Text;            
size = sizeList.Split(',');

for (int i = 0; i <= template.Length; i++)
{
    for (int j = 0; j < size.Length; j++)
    {
         //do something with template[i] and size[j]
    }
}

the values are coming from a textBox, the user may only enter one value. In which case it would only need to run once.

Upvotes: 1

Views: 98

Answers (3)

Adil
Adil

Reputation: 148110

Array is zero-based index, i.e first element has zero index. template[0] points first element. When you have only one element template[1] will refer to second element which is not present and you will probably get out of index exception.

Change

for (int i = 0; i <= template.Length; i++)

To

for (int i = 0; i < template.Length; i++)

Upvotes: 5

Lance U. Matthews
Lance U. Matthews

Reputation: 16596

Using...

for (int i = 0; i <= template.Length; i++)

...on the last iteration i will equal template.Length. template[template.Length] will always result in an IndexOutOfRangeException. Since the last element of template actually has index template.Length - 1, you should instead use...

for (int i = 0; i < template.Length; i++)

Upvotes: 1

Luca Davanzo
Luca Davanzo

Reputation: 21520

Count start from zero, you have to change your first for statement into:

for (int i = 0; i < template.Length; i++) {....}

Upvotes: 0

Related Questions