Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing null array index

Tags:

arrays

c#

Here's the thing:

object[] arrayText = new object[1];

if (arrayText[1] == null)
{
    MessageBox.Show("Is null");
}

We know that is going to be null, but it throws an exception, but I don't want to handle it in a try/catch block because that is nested in a loop and try/catch will slow it down, also it doesn't look really good:

object[] arrayText = new object[1];
try
{
    if (arrayText[1] == null)
    {

    }
}
catch (Exception ex)
{
    MessageBox.Show("Is null");
}

Thanks for you suggestions!

like image 370
Carlo Avatar asked May 28 '09 19:05

Carlo


People also ask

How do you check if an index in an array is null?

To check if an array is null, use equal to operator and check if array is equal to the value null. In the following example, we will initialize an integer array with null. And then use equal to comparison operator in an If Else statement to check if array is null. The array is empty.

Can an array index be null?

The value of an index for an array element is never null. If an expression specifies a value for an index, and the expression evaluates to the null value, the null value is returned for the array value.

What does an empty array index return?

If the length of the object is 0, then the array is considered to be empty and the function will return TRUE.

How do you check if an index in an array is empty C++?

Use array::empty() method to check if the array is empty: Instead, it examines if an array is blank or not, that is, if maybe the array's size is zero. If the size of the array becomes zero, this returns 1 which means true. Otherwise, this returns 0 which means false.


1 Answers

null is not the problem here, but the index is invalid. Arrays in C# are 0-based, so if you create an array with 1 element, only index 0 is valid:

array[0] == null

You can avoid that by checking the bounds manually before accessing the index:

if (index < array.Length) {
    // access array[index] here
} else {
    // no exception, this is the "invalid" case
}
like image 151
Lucero Avatar answered Sep 27 '22 21:09

Lucero