1

This code can throw a null pointer exception.

if (myArray[0] != null)
{
    //Do Something
}

How can I test to make sure there is an element @ index 0? Without throwing an exception when the array is empty.

1
  • 1
    First test to see if array is empty? Commented May 9, 2012 at 20:18

3 Answers 3

8

Depending on what you need to check, some combination of these conditions:

if (myArray != null && myArray.Length > 0 && myArray[0] != null)
{
    //Do Something
}
Sign up to request clarification or add additional context in comments.

Comments

2

One small change I would make to Tim's answer is this:

if (myArray != null && myArray.Any() && myArray[0] != null) 
{ 
    //Do Something 
} 

.Any checks to see if there is at least 1 without having to iterate thru the entire collection. Also, this version works with any IList< T>-implemtor.

I understand that there might be a LINQ/IEnumerable-version of .IsNullOrEmpty in some future version of .NET which would be very handy here. Heck, you could implement it as an extension method yourself!

public static class MyExtensions
{
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
    {
        return (source == null || !source.Any());
    }
}

Then your test becomes

if (!myArray.IsNullOrEmpty() && myArray[0] != null)
{
    // ...
}

3 Comments

Checking the Length or Count of an array or list (most/all ICollections, really) is an O(1) operation, it does not require iterating through the entire collection. The LINQ Any() method you suggest is slightly slower than checking the Length or Count yourself, but could be preferable, especially since it works on any IEnumerable<T>.
@Tim: You're right. I'm so used to 'assuming' nothing about what is implemmenting the interfaces I'm using. Even if the IEnumerable is really a IList LINQ is smart enough to call .Count rather than iterate. Still, I prefer the generality here.
Properties should be quick operations. If it's possible to count an IEnumerable, but takes a while, it should be a GetCount() method instead. Obviously, this isn't always true, but it's an assumption about what a property is, instead of assuming something about an interface.
1

First, you need to check if myArray is null. If it's not, then check it's elements count:

if (myArray != null && myArray.Length > 0)
{
   // myArray has at least one element
}

If first condition is false, then second will not be checked, so when myArray is null no exception will be thrown.

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.