0

I'm working on my first app, which is designed to be a to do list app. I'm a little new to all this so I hope this question isn't too much of a nuisance. I'm trying to build some code to check a string array for null. Here's the code I have


int checkForNull(string[] a, int arrayNum)
    {
        for (int x = -1; x < arrayNum ; x ++ )
        {
            if (a[x].Length == 0)
                //^^ This is a problem for some reason
            {
                return (x);
            }
        }
        return (-1);
    }

I'm trying to parse an array and return the first integer number that comes back as null. It's part of what I'm using to add new categories to my app. The error I'm receiving comes up on 'if (a[x].Length == 0)' "Array index is out of range". I've also tried 'if (a[x] == null)' but received the same error. Any ideas?

Thanks.

Ciwerk
  • 1
  • 1

1 Answers1

-1

The code should be:

int checkForNull(string[] a)
{
    for (int x = 0; x < a.Length ; x++ )
    {
        if (string.IsNullOrEmpty(a)) // Covers both cases: null empty
            return x;
    }
    return -1;
}

That said, even though the above explains your error, it's reinventing the wheel. As suggested elsewhere, array has a means for doing this directly:

int checkForNull(string[] a)
{
    return Array.FindIndex(a, string.IsNullOrEmpty);
}
Jasper Kent
  • 3,546
  • 15
  • 21