3

I looking for a way to prevent IndexOutOfRangeException when I try to access a specific array index.

I have a generic code that some times has values at array[index], and other times there is not.

so, before trying to get its value I have tried these checks:

if(array[index] != null) {
    ... Do Stuff
}

Also tried:

if(!String.IsNullOrEmpty(array[index])) {
    ... Do Stuff
}

They all trows an IndexOutOfRangeException

How could I perform this check?

3
  • Why is your code attempting to access memory outside the bounds of the array in the first place? Don't try and catch an error.. remove the error. Commented Feb 15, 2013 at 1:31
  • What is the type of array? Commented Feb 15, 2013 at 1:31
  • Just fixed. My code need some bug fixes. This is one of them. I was just curious why I was not able to check for a null index. Thanks Commented Feb 15, 2013 at 1:36

2 Answers 2

12

Very simple:

if (index < array.Length)
Sign up to request clarification or add additional context in comments.

3 Comments

While this is correct.. I feel like it should be within the loop initializer.. instead of being checked from within (I'm assuming it's a loop).
Thanks. It worked. I have to fix my code to prevent this. I was just curious why cheking for null was not working
@GuilhermeLongo: Array[999] isn't null; rather, it doesn't exist at all. The exception when you get the value in the first place, before the comparison.
0

You could also use try... catch to suppress the error. Brute?

try
{
   var x = array[index];
}
catch(Exception ex)
{
}

And better

if(array.Length > index)
   var x = array[index];

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.