C# – Testing null array index

arraysc++

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!

Best Solution

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
}