1

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.

1
  • You would probably be better served using foreach. Index math is really a waste of time in C#. Commented Dec 11, 2012 at 15:44

3 Answers 3

5

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++)
Sign up to request clarification or add additional context in comments.

Comments

1

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++)

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.