theUser
theUser

Reputation: 1396

C#, How to tell if first element of array is null, when array could possibly have no elements?

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.

Upvotes: 1

Views: 6556

Answers (3)

Vano Maisuradze
Vano Maisuradze

Reputation: 5909

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.

Upvotes: 1

n8wrl
n8wrl

Reputation: 19765

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)
{
    // ...
}

Upvotes: 2

Tim S.
Tim S.

Reputation: 56566

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

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

Upvotes: 8

Related Questions