tags:

views:

320

answers:

6

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!

+12  A: 

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
}
Lucero
I used a variation of this answer:if (i >= rawDataTables.Length || rawDataTables[i].Rows.Count == 0)
Carlo
By the way, thanks!
Carlo
You're welcome... and I assume you used "if (i <= " in your sample in the comment, not "if (i >= "... ;)
Lucero
Haha no, I did use "i >=" because the only thing I need to do is return an enum value if that "exception" happens =)
Carlo
+2  A: 

You're accessing an index that's outside the array's bounds. The array initializer takes a number for the number of elements, not the maximum index (like VB.NET). Since arrays are zero-based, your maximum index is 0 in this case.

Adam Robinson
@Adam Robinson: Technically, you answered this question.
Syed Tayyab Ali
+8  A: 
object[] arrayText = new object[1];

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

Try that? Arrays are 0 based, so trying to access arrayText[1] will give you an OutOfBoundsException. And the try/catch won't really impact your performance that much there, there isn't much in the stack at that point.

Gromer
Exceptions are still expensive, for instance the exception object has to be instantiated (including initialization). Don't use exceptions for flow control - and in this case this seems to be one of those cases.
Lucero
I'm just saying an exception at that point isn't nearly as expensive as he is thinking. There won't be an inner exception from it and it won't be bubbling up. But using a try/catch isn't a good idea in this scenario, but not because his reasoning IMO.
Gromer
This is obviously just a sample showing the problem. How can you be sure that this is not going to happen in a tight loop or another situation where the exception is expensive? Therefore, the reasoning is not wrong, even if the exception may in fact not cause performance trouble in a specific case, I think avoiding it in the first place is a good habit and the way to go IMHO.
Lucero
+1  A: 

Check the .Length of the array inside the loop, or better yet, set your loop parameters to be limited to the length of the array.

object[] arrayText = new object[1];
for (int i = 0; i < arrayText.Length; i++)
{
    doWork(arrayText[i]);
}
Dave Bauman
@Dave Bauman: +1
Syed Tayyab Ali
A: 

If you read the description on the exception that is being thrown you will see that it is "Index was outside the bounds of the array."

The new object[1] indicates that the array has one element. (1 is the count) However C# array's start indexing at 0 not 1 so an array of one element is index 0. So arrayText[0] will return null but arrayText[1] will throw an exception.

David McEwing
+1  A: 

I think the problem is not that arrayText[1] is null, it's that arrayText[1] doesnt exist - so you should get an IndexOutOfRangeException and not a null

if you're up a creek and cant easily change the code to verify the lenght you might consider adding a function that inspects the Length property (see snippit below) or overloading operator[]... both of these are a little gross but if you're in a pickle... :)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace array
{
    class Program
    {
        static object Index(object [] array, int idx)
        {
            if (idx >= array.Length)
                return null;
            else
                return array[idx];
        }
        static void Main(string[] args)
        {
            object[] blah = new object[10];
            object o = Index(blah, 10);
        }
    }
}
stuck