7

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!

7 Answers 7

27

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

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

3 Comments

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.
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.
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.
2

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.

1 Comment

@Adam Robinson: Technically, you answered this question.
1

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]);
}

Comments

1

I think the problem is not that arrayText1 is null, it's that arrayText1 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);
        }
    }
}

Comments

0

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.

Comments

0

I recently needed to find out if values in a struct array are "filled" or not at a given index. Check this out:

//the struct holding the properties:
struct Cities
        {
            public string name;

            public int inhabitansNumber;
        }

    Cities[] cities = new Cities[500]; // the struct array holding the cities

    int i = 0;
                        for (i = 0; i < cities.Length; ++i)
                        {
                            if (cities[i].Equals(default(Cities)))
                            {
                                Console.WriteLine("Please enter the city name:");
                                cities[i].name = Console.ReadLine();
                                Console.WriteLine("Please enter population:");
                                cities[i].inhabitansNumber = Convert.ToInt32(Console.ReadLine());
                                Console.WriteLine("Values added successfuly!");
                            }
                        }

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.