1

I get error

"'Index was outside the bounds of the array"

on this line string Open = array[0].ToString(); when array is empty.

I used "if" statement to see if it can be by-passed when array is empty.

However, why am I still getting this error? How can I by-pass/fix it?

if (array != null || array.Length != 0)
                {
                    int c = array.Count();
                    string Open = array[0].ToString(); <--- ERROR
                }
1
  • 1
    can you show us your array Commented Dec 16, 2018 at 7:08

5 Answers 5

9

You used the logical OR operator in your if statement. You should have used the AND operator &&.

OR will evaluate to true if any of the two conditions is true, so your if statement will be run as long as array is not null.

It should be:

if (array != null && array.Length != 0)
Sign up to request clarification or add additional context in comments.

Comments

3

This must be

if (array != null && array.Length != 0)

Comments

3

change

if (array != null || array.Length != 0)

to

if (array != null && array.Length != 0)

Comments

1

The IndexOutOfRangeException is a Runtime Exception thrown only at runtime.

According to your question, it seems like you should use check for null and length together as said by others

if (array != null && array.Length != 0)

but because you have not marked any answer as accepted so I must tell you to put your code within try and catch block like below

  try
  {
      if (array != null && array.Length != 0)
      {
         int c = array.Count();
         string Open = array[0].ToString(); <--- ERROR
      }
  }
  catch(Exception ex)
  {
      // Put breakpoint here and see inner exception by hovering your mouse cursor over ex.
  }

You will get more details in inner exception on such issues.

Comments

0

You can check an empty array's length. However, if you try to do that on a null reference you'll get an exception. Here you need && condition which will check for null and array length,

if (array != null && array.Length != 0)

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.